Search code examples
phpmysqlmysql-num-rows

mysql_num_rows in the error log


I am encountering an error. My log is as follows:

PHP Warning:  mysql_num_rows(): supplied argument is not 
a valid MySQL result resource in     
/home/domain/public_html/index.php on line 96

My code is as followsL line 96:

mysql_num_rows(mysql_query("SELECT * FROM `table` WHERE 
UNIX_TIMESTAMP(`date`)>$user_last_visit"));

What could cause this error?


Solution

  • You put two functions into each other directly:

    mysql_num_rows(mysql_query(...));
    

    Technically this is possible to do (function 1 returns something that becomes the parameter of function 2), however, in case function 1 returns something that function 2 can not deal with, you get errors.

    That happens in your case. Instead store the return value into a variable and do error handling your own:

    $result = mysql_query(...);
    if (!$result) {
        throw new Exception(sprintf('Database query failed: %s', mysql_error()));
    }
    $num_rows = mysql_num_rows($result);
    

    Proper error handling is crucial for solid programming, so take care about return values. When in doubt double-check for the function in question with the PHP manual which is really a great resource. See mysql_query.