Whats the proper way to check if mysql_query() returned any results?

后端 未结 8 1331
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-05 17:03

I tried what seemed like the most intuitive approach

$query = \"SELECT * FROM members 
          WHERE username = \'$_CLEAN[username]\'
          AND password =          


        
8条回答
  •  情深已故
    2021-02-05 17:21

    mysql_num_rows

    Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set.

    If none match, then zero will be the return value and effectively FALSE.

    $result = mysql_query($query);
    
    if(mysql_num_rows($result))
    { //-- non-empty rows found fitting your SQL query
    
      while($row = mysql_fetch_array($result))
      {//-- loop through the rows, 
       //--   each time resetting an array, $row, with the values
    
      }
    }
    

    Which is all good and fine if you only pull out of the database. If you change or delete rows from the database and want to know how many were affected by it...

    To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().

    $result = mysql_query($query);
    
    if(mysql_affected_rows())
    { //-- database has been changed 
    
    }
    
    //-- if you want to know how many rows were affected:
    echo 'Rows affected by last SQL query: ' .mysql_affected_rows();
    

    mysql_query() will only return FALSE if the query failed. It will return TRUE even if you have no rows, but successfully queried the database.

提交回复
热议问题