判断几个参数的不同状态,不同的情况写SQL语句判断条件,优化做法(仅供新手)

来源:互联网 发布:模拟投资软件 编辑:程序博客网 时间:2024/06/15 13:32

假如,有 $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语句直接的空格,千万别漏了!

0 0
原创粉丝点击