简体   繁体   中英

mysql_num_rows(): supplied argument is not a valid MySQL result resource

I need to get true if the select gets one row. However I cannot even echo the number of rows.

I get mysql_num_rows(): supplied argument is not a valid MySQL result resource

How can I do it?

$result="SELECT * FROM Users WHERE User = '$user' AND Password = '$hash' LIMIT 1";
$num_rows = mysql_num_rows(resource $result);
echo $num_rows;

You must execute your SQL query, with mysql_query() , before trying to get any result from that execution.


So, basically, your code should look like this :

// This is a QUERY, not a RESULT
$query = "SELECT * FROM Users WHERE User = '$user' AND Password = '$hash' LIMIT 1";

$result = mysql_query($query); // execute query => get a resource
if ($result) {
    // query has been executed without error
    $num_rows = mysql_num_rows($result);  // Use the result of the query's execution
    echo $num_rows;
}
else {
    // There has been an error ; deal with it
    // for debugging, displaying the error message is OK :
    echo mysql_error();
}

You have to execute the SQL query first, then you can retrieve the number of rows in the result set:

$mysql_result = mysql_query($result); // Do this first, then you can 
$num_rows = mysql_num_rows( $mysql_result);

Here is a cleaner way

$st = "SELECT COUNT(1) FoundCount FROM Users WHERE User='$user' AND Password='$hash'";
$result = mysql_query( $st );
$row = mysql_fetch_assoc( $result );
$rowfound = $row['FoundCount'];

Give it a Try !!!

Try:

$result = mysql_query("SELECT * FROM Users WHERE User = '$user' AND Password = '$hash' LIMIT 1");

Also, after executing the query, check if there were any errors. $result is not a resource in that case (it's FALSE , actually). To retrieve error details, call mysql_error() :

$query = "SELECT * FROM Users WHERE User = '$user' AND Password = '$hash' LIMIT 1";
$result = mysql_query($query);
if ($result === FALSE)
    die("Error in query $query: " . mysql_error());

It is your responsibility, however, that these error handling routines do not make it into production code, as this would propagate your database's layout. Also, check if variables interpolated into a query are properly escaped (use mysql_real_escape_string() for that).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM