function get_tags_by_criteria($gender_id, $country_id, $region_id, $city_id, $day_of_birth=NULL, $tag_id=NULL, $thread_id=NULL) {
$query = "SELECT tags.*
FROM tags, thread_tag_map, threads
WHERE thread_tag_map.thread_id = threads.id
AND thread_tag_map.tag_id = tags.id
AND threads.gender_id = $gender_id
AND threads.country_id = $country_id
AND threads.region_id = $region_id
AND threads.city_id = $city_id
AND tags.id LIKE '%$tag_id%'
AND threads.id LIKE '%$thread_id%'";
if(!$day_of_birth)
{
$query += "AND threads.min_day_of_birth <= '$day_of_birth AND threads.max_day_of_birth >= '$day_of_birth' ";
}
$query += "GROUP BY tags.name";
$result = $this->do_query($query);
return $result;
}
如果没有$ day_of_birth作为参数传递,我希望sql省略if中的2行。我用过:
$all_tags = $forum_model->get_tags_by_criteria(1, 1, 0, 0);
我想知道为什么这个sql会返回错误:
Couldn't execute query: 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 '0' at line 1
答案 0 :(得分:2)
当您使用连接(+=
)operator时,您正在使用添加(.=
)运算符。
您也应该转义输入,以避免SQL注入 - 请参阅mysql_real_escape_string()
答案 1 :(得分:1)
您的问题是您在出生日期前遗漏了'
。
将其更改为AND threads.min_day_of_birth <= '$day_of_birth'
(注意关闭'
并打开)
此外,正如其他人所指出的,你应该写$query .=
而不是$query +=
(注意.
)
您有SQL注入漏洞;你应该使用参数 Remember Bobby Tables!
答案 2 :(得分:1)
“和附加字符串中 AND 之间缺少空格
答案 3 :(得分:0)
。=用于PHP中的字符串连接,而不是+ =
答案 4 :(得分:0)
您还可以在查询中使用占位符。如果设置了选项/参数,脚本会将占位符的内容设置为相应的sql代码,否则占位符为空/ null。
e.g。
function get_tags_by_criteria($gender_id, $country_id, $region_id, $city_id, $day_of_birth=NULL, $tag_id=NULL, $thread_id=NULL) {
if ( !is_null($day_of_birth) ) {
$day_of_birth = "AND ('$day_of_birth' BETWEEN threads.min_day_of_birth AND threads.max_day_of_birth)"
}
$query = "
SELECT
tags.*
FROM
tags, thread_tag_map, threads
WHERE
thread_tag_map.thread_id = threads.id
AND thread_tag_map.tag_id = tags.id
AND threads.gender_id = $gender_id
AND threads.country_id = $country_id
AND threads.region_id = $region_id
AND threads.city_id = $city_id
AND tags.id LIKE '%$tag_id%'
AND threads.id LIKE '%$thread_id%'
{$day_of_birth}
GROUP BY
tags.name
";
$result = $this->do_query($query);
return $result;
}
编辑:如前所述:记住可能的sql注入。