Handling Query Failures in PHP MySQL Extensions
When attempting to extract data from a MySQL table, occasionally, errors such as "mysql_fetch_array() expects parameter 1 to be resource, boolean given" may arise. This error indicates that the query function failed, resulting in a boolean value ("false") instead of the expected resource handle.
In the provided PHP code:
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username'); while($row = mysql_fetch_array($result)) { echo $row['FirstName']; }
The error occurs because the query function (mysql_query) can return either true upon successful execution or false in case of failure. It should be noted that the provided SQL statement may fail due to various reasons, such as invalid syntax or non-existent table.
To resolve this, you should check the result of the query function before trying to fetch rows using mysql_fetch_array. If $result evaluates to false, it signifies that the query failed, and you should handle the error appropriately.
For the Deprecated MySQL Extension:
if($result === FALSE) { trigger_error(mysql_error(), E_USER_ERROR); }
For the MySQLi Extension:
if($result->errno) { // Log or output the error message }
The above is the detailed content of How Can I Handle Query Failures When Using PHP's MySQL Extensions?. For more information, please follow other related articles on the PHP Chinese website!