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?
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
.
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?
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.
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.