Validating a valid MySQL result resource

I have this code:

$rows = array(); $res = mysql_query($someQuery); if(!mysql_errno()) while($row = mysql_fetch_assoc($res)) $rows[] = $row; 

$someQuery is an arbitrary query that I write to the form. Mysql_errno catches the case when I write a mysql query with errors in it. But I just found that when I make the query "Delete from table_name", this is certainly not an error, but at the same time mysql_fetch_assoc fails with the argument "Warning: mysql_num_rows (): the supplied argument is not a valid MySQL resource result in /blah/blah/file.php on line x ".

I tried to find it in the manual (maybe I'm just blind), but is there a function I can use to check if $ res is a valid MySQL result resource or not?

+6
php mysql resultset
source share
6 answers

if ($res) should work fine to check if it is a resource. is_resource () will determine if its a valid resource.

You can also check mysql_affected_rows to determine if it is INSERT / UPDATE / etc

+7
source share

Along with is_resource() you can use get_resource_type() to check if this is a MySQL resource.

 $res_type = is_resource($res) ? get_resource_type($res) : gettype($res); if(strpos($res_type, 'mysql') === false) { echo 'Invalid resource type: ' . $res_type; } 

get_resource_type() may return "mysql link" or "mysql link persistent" depending on your type of connection.

+3
source share

mysql_query() returns true or false so you can check it like this:

 if($res) { // The query succeeded. } 
+2
source share
+2
source share

If you insert, UPDATE, DELETE or DELETE via mysql_query , then it will return only true or false (depending on the success of the operation).

I'm not sure what you expect the resource to contain in this instance?

If you need the number of rows affected, you can use mysql_affected_rows() .

0
source share

Maybe just change the condition to:

 if(!mysql_errno() && @mysql_num_rows($res) > 0) 

There will be no conditional failure if there are no lines, and @ will suppress the warning.

0
source share

All Articles