mysql_fetch_assoc() expects parameter 1 to be resource, provided boolean: Reason and Solution

Mysql_fetch_assoc() expects parameter 1 to be resource but boolean is provided can be caused due to various reason. We have to analyse the code and hand the issue accordingly.

NOTE: The mysql_ functions are deprecated and have been removed in php version 7. So we are going to use mysqli_function

Reason:

If we are using mysqli_fetch_assoc function then we are required to provide mysqli_query result value as parameter. mysqli_query is null then such error might rise.

Solution:

Example:

Lets fetch all the names from the database table which matches with the name ‘sam’ and this name sam we are getting from url.

$name=mysqli_real_escape_string($conn,$_GET[“name”]);

$sql=”select * from users where name like ‘”.$name.”‘”;

$result=mysqli_query($conn,$sql);

if(!$result){

die(mysql_error);

}

if(mysqli_num_rows($result)>0){

while($row=mysqli_fetch_assoc($result)){

echo $row[“name”].'<br>’;

}

}

In the above code we are checking whether $result value exists or not. If does not exist, then it will die other wise going to give us user names.

The same result could also achieved using mysqli Object Oriented style as below.

$name = $mysqli->escape_string($_GET[‘name’]);
$result = $mysqli->query(“SELECT * FROM Users WHERE Name LIKE ‘$name'”);

if($result === FALSE) {
echo “Error: “.$mysqli->error; // or $mysqli->error_list
}else {

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo $row[“name”].'<br>’;
    }
} else {
    echo “0 results”;
}

}

The same result could also be achieved using mysqli prepared statement.

$pStatement = $mysqli->prepare(‘SELECT * FROM Users WHERE Name LIKE ?’);
if ( !$pStatement ) {
echo “Error: “.$mysqli->error;
}else if ( !$pStatement->bind_param(‘s’, $_GET[‘name’]) ) {
echo “Error: “.$stmt->error;
}else if ( !$pStatement->execute() ) {
echo “Error:”.$stmt->error;
}else {
$result =$pStatement->get_result();
foreach( $result as $row ) {

echo $row[“name”].'<br/>’;

}
}

Note: During testing, die function is useful. In real environment, you must redirect and show proper message.

Note: It is not at all wise to show error messages in PHP / HTML webpages. Only admins should view these error messages.