Home >Database >Mysql Tutorial >Why Does `mysql_fetch_array()` Return a Boolean Instead of a Resource, and How Can I Fix It?
MySQL Resource Error: mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc..."
When attempting to interact with a MySQL database, developers may encounter error messages such as "mysql_fetch_array() expects parameter 1 to be resource, boolean given." This issue arises when a query fails and the function receiving the query's result as an argument interprets it as a boolean instead of a resource.
To resolve this error, the first step is to verify that the query executed successfully. Before passing the result to functions like mysql_fetch_array(), evaluate the result variable using mysql_query(). If it returns false, the query has failed and further processing should not occur.
Handling Error Conditions in MySQL Extension
The deprecated mysql_ extension provides a way to retrieve the error message associated with a failed query using mysql_error(). By incorporating this check into the code, developers can trigger an error and provide meaningful information to handle the issue.
Example with mysql_ extension:
$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']; }
By following these steps, developers can diagnose and resolve the issue where mysql_fetch_array() expects a resource but receives a boolean, ensuring smooth data retrieval from MySQL tables.
The above is the detailed content of Why Does `mysql_fetch_array()` Return a Boolean Instead of a Resource, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!