Graham
Graham

Reputation: 1473

using WHERE clause as a variable in MySQL query not working

This is really weird.

This query obviously works:

$query = mysql_query("SELECT * FROM restaurant_page WHERE title LIKE '%$search_title%'");

But, this doesn't:

$category = 'restaurant_page';

$query = mysql_query("SELECT * FROM '$category' WHERE title LIKE '%$search_title%'");

With the second query, I get the resource boolean error.

$category is table the user wants to search from. When I print out the query with the variable, it's the exact same as the first one. Why wouldn't this work?

Upvotes: 0

Views: 1436

Answers (7)

Leysam Rosario
Leysam Rosario

Reputation: 369

LOL. This makes my day. remove the quote on the $category. Im sure this is just a funny mistake. All of us made some mistake. hehe

To solve this change the ' to "

$query = mysql_query("SELECT * FROM ".$category." WHERE title LIKE '%$search_title%'");

Upvotes: 0

knittl
knittl

Reputation: 265864

Don't use single quotes around your table name, use backticks (`) instead:

$query = mysql_query("SELECT * FROM `$category` WHERE title LIKE '%$search_title%'");

NB. Please make sure that $category and $search_title are not plain user provided variables

Upvotes: 1

Johannes Klauß
Johannes Klauß

Reputation: 11040

You should always seperate the variables from the actual string. Do something like this:

$category = "restaurant_page";

$query = mysql_query("SELECT * FROM `".$category."` WHERE title LIKE
'%".$search_title."%'");

Upvotes: 0

Grouchal
Grouchal

Reputation: 9796

Why have you got quotes around $category - remove these and it should work.

Upvotes: 0

Michael Berkowski
Michael Berkowski

Reputation: 270767

Remove the single quotes from '$category'.

"SELECT * FROM '$category' WHERE title LIKE '%$search_title%'"
---------------^^^^^^^^^^^^

If needed, surround $category with backticks. This is only necessary if $category contains a MySQL reserved keyword. However, since it is a variable that could become a possiblity.

$query = mysql_query("SELECT * FROM `$category` WHERE title LIKE '%$search_title%'");

Of course, please don't forget to escape $category since it may be user input. We assume you have already done so for $search_title as well.

$category = mysql_real_escape_string($category);

Upvotes: 1

Jonathan Kuhn
Jonathan Kuhn

Reputation: 15311

in the mysql query, don't put quotes around $category.

$query = mysql_query("SELECT * FROM $category WHERE title LIKE '%$search_title%'");

Upvotes: 1

Jacob Mattison
Jacob Mattison

Reputation: 51072

Does the query created with the variable have quotes areound the table name? That seems like a mistake to me.

Upvotes: 2

Related Questions