Home >Backend Development >PHP Tutorial >Why Does `mysql_fetch_array()` Show 'expects parameter 1 to be resource' and How Can I Fix It?

Why Does `mysql_fetch_array()` Show 'expects parameter 1 to be resource' and How Can I Fix It?

Linda Hamilton
Linda HamiltonOriginal
2024-12-22 20:17:12561browse

Why Does `mysql_fetch_array()` Show

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:

  1. Check the Query Result: Verify that the mysql_query() call does not return false by checking its result.
  2. Handle Query Failures: If the query does fail, trigger an error or handle it appropriately.
  3. Ensure Proper Parameter: Pass the correct result resource to the retrieval function rather than the boolean value that resulted from the failed query.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn