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:

<?php

//Our example MySQL query. Notice how I have intentionally
//left out the * or column names that I want to select.
$result = mysql_query("SELECT FROM my_table");

while($row = mysql_fetch_array($result)){
    //Do something.
}

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 $result variable 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:

<?php

//Our example MySQL query. Notice how I have intentionally
//left out the * or column names that I want to select.
$result = mysql_query("SELECT FROM my_table");

//Check to see if the query failed.
if($result === false){
    throw new Exception(mysql_error($connection));
}

while($row = mysql_fetch_array($result)){
    //Do something.
}

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.