0

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?

cytinus
  • 5,467
  • 8
  • 36
  • 47
Dima Deplov
  • 3,688
  • 7
  • 45
  • 77
  • [So many duplicates](http://stackoverflow.com/search?q=mysql_num_rows%28%29%3A+supplied+argument+is+not++a+valid+MySQL+result+resource+in) – Mike B Apr 15 '12 at 21:52

4 Answers4

0

I would try rearranging the code

$sql = "SELECT * FROM `table` WHERE UNIX_TIMESTAMP(`date`) > $user_last_visit";
$result = mysql_query($sql) or die(mysql_error());
echo mysql_num_rows($result);

I can't tell from your code but you are creating a connection to the mysql server?

Dale
  • 10,384
  • 21
  • 34
0

If you only want to count the rows, use the COUNT(*) keyword in the query; otherwise, the data base will prepare the whole resulting rows for output although you don't need them.

SELECT COUNT(*)
FROM `table`
WHERE UNIX_TIMESTAMP(`date`) > $user_last_visit

Then, simple execute the query:

$result = mysql_query($query);
list($count) = mysql_fetch_array($result);

Anyway, your query throws an error; there should be another warning showing the error. You can use mysql_error() to find out the error otherwise.

Yogu
  • 9,165
  • 5
  • 37
  • 58
0

According to http://php.net/manual/en/function.mysql-query.php mysql_query returns "For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error."

So try doing

$query = "SELECT * FROM `table` WHERE UNIX_TIMESTAMP(`date`)>$user_last_visit"
$resource = mysql_query($query) or die("Error: ". mysql_error(). " with query ". $query);
mysql_num_rows($resource);

And then see what happens.

Mads
  • 724
  • 3
  • 10
0

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.

hakre
  • 193,403
  • 52
  • 435
  • 836