mysql_fetch_array() expects parameter 1 to be resource
When retrieving data from mysql tables sometimes we might have got this error: mysql_fetch_array() expects parameter 1 to be resource.
This warning tells us, we are passing an empty result variable for processing, for example:
In the above example, we are passing $result variable to mysql_fetch_array function without checking whether the data actually exist or not. When the query didnot find any records, we get this mysql_fetch_array() expects parameter 1 to be resource error message.
To fix this issue we must check that result variable before processing. Have a look at this example:
As in the example we must validate mysql result variable before passing to mysql functions like mysql_fetch_array, mysql_fetch_assoc,mysql_mum_rows etc.
This warning tells us, we are passing an empty result variable for processing, for example:
$result = mysql_query("SELECT * FROM users WHERE username = '$user'");
while($row = mysql_fetch_array($result)){
echo $row['name'];
}
In the above example, we are passing $result variable to mysql_fetch_array function without checking whether the data actually exist or not. When the query didnot find any records, we get this mysql_fetch_array() expects parameter 1 to be resource error message.
To fix this issue we must check that result variable before processing. Have a look at this example:
$result = mysql_query("SELECT * FROM users WHERE username = '$user'");
if($result===false){
echo "No record found for '$user'";
}else{
while($row = mysql_fetch_array($result)){
echo $row['name'];
}
}
As in the example we must validate mysql result variable before passing to mysql functions like mysql_fetch_array, mysql_fetch_assoc,mysql_mum_rows etc.
Comments (0)