Recent Posts

Showing posts with label mysql_fetch_array. Show all posts
Showing posts with label mysql_fetch_array. Show all posts

PHP: mysql_fetch_array() expects parameter 1 to be resource (or mysqli_result), boolean given

If you get this message:

mysql_fetch_array() expects parameter 1 to be resource, boolean given

or

mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given

Check the $result variable or whatever name you put it before passing it to mysql_fetch_array. You'll find that it's false because the query failed. See the mysql_query documentation for possible return values and suggestions for how to deal with them.

$username = mysql_real_escape_string($_POST['username']);
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '$username'");

if($result === FALSE) {
    die(mysql_error()); // TODO: better error handling
}

while($row = mysql_fetch_array($result))
{
    echo $row['FirstName'];
}
This example is only to illustrate what should be done (error handling), not how to do it. Production code shouldn't use or die when outputting HTML, else it will (at the very least) generate invalid HTML. Also, database error messages shouldn't be displayed to non-admin users, as it discloses too much information.

How to solve: Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given

First and foremost:

This happens when you try to fetch data from the result of mysql_query but the query failed.

This is a warning and won't stop the script, but will make your program wrong.

You need to check the result returned by mysql_query by:

$res = mysql_query($sql);
if (!$res) {
   die(mysql_error());
}
// after checking, do the fetch