Understanding MySQL Resource Error
When attempting to retrieve data from a MySQL table using MySQL procedural functions, such as mysql_fetch_array(), you may encounter the error: "mysql_fetch_array() expects parameter 1 to be resource, boolean given". This error typically occurs when the query fails due to various reasons.
To resolve this issue, it's crucial to check the value of the $result variable before passing it to the mysql_fetch_array() function. If the query fails, $result will be set to false.
For example, in your provided PHP code:
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
You have a syntax error in your SQL query. The correct syntax for LIKE operator is to use single quotes around the search string:
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '$username'");
Once you correct the syntax error, you will need to check if $result is not false, as follows:
if($result !== FALSE) { while($row = mysql_fetch_array($result)) { echo $row['FirstName']; } } else { trigger_error(mysql_error(), E_USER_ERROR); }
The mysql_error() function provides more details about the query failure, which you can display to the user or log for debugging purposes. By handling query errors properly, you can avoid the PHP resource error and retrieve data successfully from the MySQL table.
The above is the detailed content of Why Does `mysql_fetch_array()` Return 'expects parameter 1 to be resource, boolean given'?. For more information, please follow other related articles on the PHP Chinese website!