我无法解释为什么我的查询会返回错误。我用PHP生成它。
$column = "display_name";
$criteria = "Steven";
$query = "
SELECT
m.user_id AS id, m.email_address, m.display_name, m.status, UNIX_TIMESTAMP(m.join_date) AS join_date,
l.listing_id, COUNT(l.member_id) AS total_listings,
g.group_id AS group_id, g.title AS group_title
FROM users AS m
LEFT JOIN listings as l on m.user_id = l.member_id
LEFT JOIN groups AS g on m.group_id = g.group_id";
if($column == "display_name"){
$query .= '
WHERE m.display_name LIKE \'%'.$criteria.'\'%';
} else {
$query = "
WHERE m.".$column." = '$criteria'";
}
$query .="
GROUP BY m.user_id";
以上代码产生以下内容:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '% GROUP BY m.user_id' at line 8
SELECT m.user_id AS id, m.email_address, m.display_name, m.status, UNIX_TIMESTAMP(m.join_date) AS join_date, l.listing_id, COUNT(l.member_id) AS total_listings, g.group_id AS group_id, g.title AS group_title FROM users AS m LEFT JOIN listings as l on m.user_id = l.member_id LEFT JOIN groups AS g on m.group_id = g.group_id WHERE m.display_name LIKE '%Steven'% GROUP BY m.user_id
我尝试过使用LIKE %$criteria%
和LIKE '%$criteria%'
,我不知道为什么它们都不起作用。有什么想法吗?
答案 0 :(得分:0)
您的百分比超出了引号:
$query .= '
WHERE m.display_name LIKE \'%'.$criteria.'%\'';
使用双引号可以使事情变得更清晰:
$query .= "
WHERE m.display_name LIKE '%$criteria%'";
我当然希望你能够很好地逃避这些数据。
答案 1 :(得分:0)
因为您的查询正在被解释为
WHERE m.display_name LIKE '%text'%
在这里,您在%
签名之前使用单引号。它应该是'%text%'
而不是'%text'%
。像这样修复它
$query .= '
WHERE m.display_name LIKE \'%'.$criteria.'%\'';
最好在外面使用双引号来消除所有这些混淆。像这样:
$query .= "
WHERE m.display_name LIKE '%$criteria%'";