using WHERE clause as a variable in MySQL query not working

匿名 (未验证) 提交于 2019-12-03 01:45:01

问题:

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?

回答1:

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



回答2:

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



回答3:

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

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


回答4:

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); 


回答5:

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



回答6:

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."%'"); 


回答7:

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%'"); 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!