在 MySQL 查询中使用 WHERE 子句作为变量不起作用 [英] using WHERE clause as a variable in MySQL query not working
本文介绍了在 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
这篇关于在 MySQL 查询中使用 WHERE 子句作为变量不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文