在 MySQL 查询中使用 WHERE 子句作为变量不起作用

问题描述:

这真的很奇怪.

这个查询显然有效:

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

但是,这不会:

$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 是用户想要搜索的表格.当我用变量打印出查询时,它与第一个完全相同.为什么这行不通?

$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?

不要在表名周围使用单引号,而是使用反引号 (`):

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

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

注意.请确保 $category$search_title 不是普通的用户提供的变量

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