Thursday, 9 August 2018

Mysql_fetch_array() Expects Parameter 1 To Be Resource, Boolean Given.

This is probably one of the most common PHP errors. More often than not, this warning occurs whenever the developer in question has failed to make sure that their MySQL query is being executed successfully. Note that this error can occur with any of the MySQL fetch functions: mysql_fetch_arraymysql_fetch_assoc and mysql_fetch_row.
Lets take a look at the error message in question:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in file.php on line 7
Basically, the function mysql_fetch_array expects a resource. Instead, it is receiving a boolean value. In 99.99% of cases, you will find that this boolean variable will be a FALSE value.
Here’s an example:
In the code snippet above, I have intentionally created a malformed SQL query that will fail (the query will fail because I didn’t specify what fields should be returned). When the query above fails, the function mysql_query will return a boolean FALSE value instead of a resource.  This means that the variable $result will contain a boolean FALSE value.
Because I failed to check if my query was successful or not, I ended up passing the $resultvariable to mysql_fetch_array, which spits out the error:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given
Really, in circumstances like this, it is better that the script stops executing as soon as the query fails. Personally, I prefer to throw an exception like so:
In the code above, I check to see if $result is a boolean FALSE value. If it is, then I throw an exception containing the last MySQL error.

0 comments:

Post a Comment