Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to prevent this error : Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in ... on line 11 [duplicate]

Possible Duplicate:
PHP Error: mysql_fetch_array() expects parameter 1 to be resource, boolean given

I'm very confused with this error, it shows when I try to return a result from the DB that doesn't exist ... I tried mysql_num_rows() but it returns the same error but instead of mysql_fetch_assoc expects ... it says mysql_num_rows() expects ...

I set error_reporting(0) to avoid showing this error, but I'm not satisfied with this solution ...

like image 870
Naughty.Coder Avatar asked Jun 27 '10 23:06

Naughty.Coder


2 Answers

Here's the proper way to do things:

<?PHP
$sql = 'some query...';
$result = mysql_query($q);

if (! $result){
   throw new My_Db_Exception('Database error: ' . mysql_error());
}

while($row = mysql_fetch_assoc($result)){
  //handle rows.
}

Note the check on (! $result) -- if your $result is a boolean, it's certainly false, and it means there was a database error, meaning your query was probably bad.

like image 125
timdev Avatar answered Oct 15 '22 18:10

timdev


You must check if result returned by mysql_query is false.

$r = mysql_qyery("...");
if ($r) {
  mysql_fetch_assoc($r);
}

You can use @mysql_fetch_assoc($r) to avoid error displaying.

like image 24
Pavel Strakhov Avatar answered Oct 15 '22 18:10

Pavel Strakhov