'mysql_result is defined but mysql_free_result warns it expected a resource

This code tests to see if there was a result before freeing it up:

$result = mysql_query($query) or die("$query\n\n" . mysql_error());
$id = mysql_insert_id();
if ($result) { mysql_free_result($result); }

But it gives this warning:

mysql_free_result() expects parameter 1 to be resource, boolean given in /foo/bar/etc.php

What am I doing wrong?



Solution 1:[1]

Since you have called mysql_insert_id(), I assume you performed an INSERT query rather than a SELECT. In that case (as with others where no rowset is returned), $result is merely a boolean TRUE on success, not a result resource. There's no need to free it, and indeed trying to free it results in a warning.

From the documentation on mysql_query():

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.

For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.

However, that doesn't mean you shouldn't error-check it.

$result = mysql_query($query);
if ($result) {
  $id = mysql_insert_id();
}
else echo mysql_error();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community