Understanding the "mysql_fetch_..." Expecting Resource Error
When using MySQL functions such as mysql_fetch_array(), mysql_fetch_assoc(), mysql_fetch_row(), and mysql_num_rows, you may encounter the error: "mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource."
The error indicates that the first parameter to the function is not a valid database resource. A database resource is typically obtained from a successful call to mysql_query(). If mysql_query() fails to execute the query, it returns false.
Addressing the Issue
To resolve this error, you need to ensure that the query is successfully executed before passing the result resource to the fetch functions. This involves checking the return value of mysql_query() and handling the error condition accordingly.
Example for mysql_extension
<?php $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, mysql_real_escape_string() prepares the username string for the query to prevent SQL injections. We check the return value of mysql_query() and trigger a user error if the query fails. If the query is successful, we can safely use the result resource in the mysql_fetch_array() function.
The above is the detailed content of Why Do MySQL Fetch Functions Return 'expects parameter 1 to be resource'?. For more information, please follow other related articles on the PHP Chinese website!