"php warning mysql_fetch_assoc": A Mistake
This article delves into the issue of encountering the "mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource" warning when accessing information from a MySQL database using PHP.
Typically, the mysql_* functions in PHP operate in a particular manner, as seen below:
<code class="php">$id = 1234; $query = 'SELECT name, genre FROM sometable WHERE id=' . $id; // $query is a string with the MySQL query $resource = mysql_query($query); // $resource is a *MySQL result resource* - a mere link to the result set while ($row = mysql_fetch_assoc($resource)) { // $row is an associative array from the result set print_r($row); // do something with $row }</code>
In this example, $resource represents a valid MySQL result resource, obtained from executing the query. When this resource is passed to mysql_fetch_assoc, it extracts associative arrays from the result set. However, if something other than a valid result resource is passed to mysql_fetch_assoc (e.g., a string, object, or boolean), the function raises an error.
One common pitfall is passing something other than a valid query string to mysql_query. In such cases, mysql_query will return FALSE, which is not a valid result resource. Attempting to pass FALSE to mysql_fetch_assoc will trigger the warning.
The above is the detailed content of Why Am I Getting the \'mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource\' Warning in PHP?. For more information, please follow other related articles on the PHP Chinese website!