Home >Backend Development >PHP Tutorial >Why Does `mysql_fetch_array()` Show 'expects parameter 1 to be resource' and How Can I Fix It?
Understanding the "mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource" Error
When you encounter this error, it indicates that one of the database retrieval functions (e.g., mysql_fetch_array(), mysql_fetch_assoc(), etc.) is being called with an invalid parameter. Specifically, the parameter should be a resource representing a database result set, but it is instead a boolean value.
The Cause of the Error
The root cause of this error is typically a failed database query. When a query fails, the mysql_* functions/methods return false, which can be misinterpreted as a boolean value. As a result, when you subsequently call a retrieval function with the false result, it leads to this error.
Fixing the Error
To resolve this issue, you must follow these steps:
Example
Consider the following code:
$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']; }
In this example, we first check the result of mysql_query() and trigger an error if the query fails. Then, we correctly pass the $result resource to the mysql_fetch_array() function. This ensures that the appropriate parameter is used, preventing the error from occurring.
The above is the detailed content of Why Does `mysql_fetch_array()` Show 'expects parameter 1 to be resource' and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!