可以在WHERE之后的Mysql查询中使用变量

时间:2012-11-29 20:10:29

标签: php mysql

以下查询有效并返回结果

$query = "SELECT * FROM table WHERE District = '" . $var . "' ORDER BY Form_Date DESC";

好像我用'#34; District"使用变量,它不起作用

$query = "SELECT * FROM table WHERE '" . $distvar . "' = '" . $var . "' ORDER BY Form_Date DESC";

这个问题出了什么问题?我怎样才能让它发挥作用?

2 个答案:

答案 0 :(得分:5)

删除您正在测试的字段周围的引号,或者用反引号替换它们以避免将您从mysql解析器中误认为是可能的保留字:

$query = "SELECT * FROM `table` WHERE `" . $distvar . "` = '" . $var . "' ORDER BY Form_Date DESC";

答案 1 :(得分:1)

试试这个:

$query = "SELECT * FROM table WHERE `" . $distvar . "` = '" . $var . "' ORDER BY Form_Date DESC";

$query = "SELECT * FROM table WHERE " . $distvar . " = '" . $var . "' ORDER BY Form_Date DESC";