Checking for valid MySQL result resource

2019-02-13 16:01发布

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?

6条回答
ら.Afraid
2楼-- · 2019-02-13 16:39

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.

查看更多
Ridiculous、
3楼-- · 2019-02-13 16:41

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

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

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

查看更多
萌系小妹纸
4楼-- · 2019-02-13 16:43

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

if($res) {
    // The query succeeded.
}
查看更多
再贱就再见
6楼-- · 2019-02-13 16:55

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

查看更多
贪生不怕死
7楼-- · 2019-02-13 17:00

Perhaps just change the condition to:

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

The conditional will fail if there's no rows, and @ will suppress the warning.

查看更多
登录 后发表回答