简体   繁体   English

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

[英]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. $category是用户要搜索的表。 When I print out the query with the variable, it's the exact same as the first one. 当我使用该变量打印查询时,它与第一个查询完全相同。 Why wouldn't this work? 为什么不起作用?

Does the query created with the variable have quotes areound the table name? 用变量创建的查询的表名是否带有引号? That seems like a mistake to me. 对我来说,这似乎是一个错误。

在mysql查询中,不要在$ category前后加上引号。

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

Remove the single quotes from '$category' . 删除'$category'的单引号。

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

If needed, surround $category with backticks. 如果需要,请在$category加上反引号。 This is only necessary if $category contains a MySQL reserved keyword. 仅当$category包含MySQL保留关键字时才需要这样做。 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. 当然,请不要忘记转义$category因为它可能是用户输入的。 We assume you have already done so for $search_title as well. 我们假设您已经为$search_title做过。

$category = mysql_real_escape_string($category);

Don't use single quotes around your table name, use backticks ( ` ) instead: 不要在表名周围使用单引号,而应使用反引号( ` ):

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

NB. NB。 Please make sure that $category and $search_title are not plain user provided variables 请确保$category$search_title不是普通用户提供的变量

为什么在$ category周围有报价-删除它们,它应该可以工作。

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

LOL. 大声笑。 This makes my day. 这让我开心。 remove the quote on the $category. 删除$ 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%'");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM