0

Getting this error mysql_fetch_assoc() expects parameter 1 to be resource, boolean given when I return my query

$query = mysql_query("SELECT * FROM tempusers
    WHERE 'firstname' LIKE '%$data%' 
    OR 'lastname' LIKE '%$data%'
    OR 'description' LIKE '%$data%'
    OR 'title' LIKE '%$data%'");

if (! $query){
    echo'Database error: ' . mysql_error();
}
while($row=mysql_fetch_assoc($query)){
    $description = $row['description'];
    echo $description;
}

Specifically, the while loop. Not understanding why I'm getting. I'm thinking it's because of my use of LIKE, I am unsure if I am using the wildcard's %% correctly with my query. I would appreciate knowing how to rid of this error and why it happened

newfurniturey
  • 37,556
  • 9
  • 94
  • 102
Octavius
  • 583
  • 5
  • 19

2 Answers2

4
  • use CONCAT() function
  • use backtick instead of single quote on column names (but in this case it is not required since your column name is not a reserved keyword or it does not contain invalid characters on it)

query,

SELECT * FROM tempusers
WHERE  `firstname` LIKE CONCAT('%', '$data', '%')
    OR `lastname` LIKE CONCAT('%', '$data', '%')
    OR `description` LIKE CONCAT('%', '$data', '%')
    OR `title` LIKE CONCAT('%', '$data', '%')

one more thing, your query is vulnerable with SQL Injection, please take time to read the article below,

Community
  • 1
  • 1
John Woo
  • 258,903
  • 69
  • 498
  • 492
1
why it happened?

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error
Also for mysql_fetch_assoc(), the argument must be a proper resource not an object like FALSE in this case.

How to rid of this error? 

Since the error is due to your query whose execution returns FALSE, this may be the solution to that.

$query = mysql_query("SELECT * FROM `tempusers`
        WHERE `firstname` LIKE '%" . $data . "%'
        OR `lastname` LIKE '%" . $data . "%'
        OR `description` LIKE '%" . $data . "%'
        OR `title` LIKE '%" . $data . "%'");
Ravi
  • 2,078
  • 13
  • 23