假如,有 $a,$b,$c这三个变量,复杂的做法是这样的:
//假如三个值都不为空
if($a != null && $b != null && $c != null){
$where = "test1 =a and test2 = b and test3 = c ";
}
//假如$a为空
if($a == null && $b != null && $c != null){
$where = "test2 = b and test3 = c";
}
//假如$b为空
if($a != null && $b == null && $c != null){
$where = "test1 = a and test3 = c";
}
//假如$c为空
if($a != null && $b != null && $c == null){
$where = "test1 = a and test2 = b";
}
//假如$a和$b为空
if($a == null && $b == null && $c != null){
$where = "test3 = c";
}
//假如$a和$c为空
if($a == null && $b != null && $c == null){
$where = "test2 = b";
}
//假如$b和$c为空
if($a != null && $b == null && $c == null){
$where = "test1 = a";
}
//假如都为空
if($a == null && $b == null && $c == null){
$where = "";
}
这样的代码量比较大,而且写起来非常乱,很容易就把变量搞错了。这时候就需要优化一下我们的代码。如下:
$where = "1=1";
if($a != null){
$where .=" and test1 = a ";
}
if($b != null){
$where .= " and test2 = b ";
}
if($c != null){
$where .= " and test3 = c ";
}
//这个时候,就可以把$where打印出来看看
echo $where;
一定要注意,SQL语句直接的空格,千万别漏了!