背景
当筛选时候有不确定的条件但是需要一条SQL语句组合起来,where和and需要组合,可以这样实现
$sql = "select * from table ";
$whr= []; //定义空数组
//筛选组合条件
if(!empty($a)){
$whr[] = " age = ".$a;
}
if(!empty($sex)){
$whr[] = " sex = ".$sex;
}
...
//组合where条件
if (!empty($whr)) {
$sql .= ' WHERE ' . implode(' AND ', $whr);
}
//排序
$sql = " order by id";
echo $sql;
网友评论