Home >Backend Development >PHP Tutorial >Why Does MySQL Fetching Throw a 'Resource Expectation Failure' Error?
Error Thrown: Resource Expectation Failure
When attempting to access data from a MySQL table, you may encounter an error that reads: "mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource, boolean given."
Explanation
This error is triggered when a MySQL query fails, often due to incorrect syntax, logic errors, missing fields, or database connectivity issues. As a result, the $result variable assigned from the mysql_query() function returns false.
Solution
To resolve this error, you must check whether the $result variable is false before attempting to perform any further operations. The mysql_query() function documentation provides details on possible return values and suggests steps to handle failures.
For the mysql_ extension, use mysql_error() to obtain error details and trigger an appropriate error message using trigger_error(). The following revised code includes error handling:
$username = mysql_real_escape_string($_POST['username']); $password = $_POST['password']; $result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '$username'"); if ($result === FALSE) { trigger_error(mysql_error(), E_USER_ERROR); } while ($row = mysql_fetch_array($result)) { echo $row['FirstName']; }
The above is the detailed content of Why Does MySQL Fetching Throw a 'Resource Expectation Failure' Error?. For more information, please follow other related articles on the PHP Chinese website!