我有这个PHP代码
$coma_count=substr_count($Hob,',');
if ($coma_count==0) {
$query="SELECT * FROM user_opt WHERE Interests='$Hob' LIMIT 80";
}else{
$expl=explode(',',$Hob);
for ($i=0; $i <=$coma_count; $i++) {
$query.=" UNION SELECT * FROM users WHERE Interests LIKE '%{$expl[$i]}%'";
}
}
$sql=$con->query($query." ORDER BY RAND()") or die($con->error);
$coma_count
的数量从0到112不等,问题是$coma_count
为0时(表示只选择了国家/地区)我的查询看起来像SELECT * FROM user_opt WHERE Country='$Countr' LIMIT 80 ORDER BY RAND()
这不是SQL接受了。我该怎么办?
答案 0 :(得分:1)
创建一个$limit
变量,如果需要,设置它,然后追加它:
$limit = '';
$coma_count=substr_count($Hob,',');
if ($coma_count==0) {
$query="SELECT * FROM user_opt WHERE Interests='$Hob'";
$limit = " LIMIT 80";
}else{
$expl=explode(',',$Hob);
for ($i=0; $i <=$coma_count; $i++) {
$query.=" UNION SELECT * FROM users WHERE Interests LIKE '%{$expl[$i]}%'";
}
}
$sql=$con->query($query." ORDER BY RAND()".$limit) or die($con->error);