gpt4 book ai didi

php - if函数在sql查询中?

转载 作者:太空宇宙 更新时间:2023-11-03 11:19:51 25 4
gpt4 key购买 nike

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 中的两行。我用过:

$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

最佳答案

当您应该使用连接运算符 (.=) 时,您却使用了加法运算符 (+=) operator .

您也应该转义您的输入,以避免 SQL 注入(inject) - 参见 mysql_real_escape_string()

关于php - if函数在sql查询中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1875220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com