Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for 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 in to a form. The mysql_errno catches the case when I write a mysql query with errors in it. But, I just discovered that when I do a "Delete from table_name" query, it of course is not an error, but at the same time the mysql_fetch_assoc fails with a "Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /blah/blah/file.php on line x".

I've tried to look for 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?

like image 782
Svish Avatar asked Apr 23 '09 19:04

Svish


3 Answers

if ($res) should work fine to check if it's a resource. is_resource() will determine if its a valid resource at all.

You could also check mysql_affected_rows to try to determine if it's an INSERT/UPDATE/etc

like image 91
Matt Avatar answered Oct 16 '22 16:10

Matt


Along with is_resource() you can use get_resource_type() to check whether it 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 connection type.

like image 3
Caner Avatar answered Oct 16 '22 16:10

Caner


Check http://www.lampdocs.com/blog/2010/10/how-to-check-that-a-php-variable-is-a-mysql-resource/ for the solution. Hope this helps.

like image 2
Vladimir Avatar answered Oct 16 '22 15:10

Vladimir