0
点赞
收藏
分享

微信扫一扫

where = '1=1' 有什么作用?



下面代码首先定义$where= '1=1',后面就可以不用去判断是否存在$where;简化了判断流程;

1=1 是永恒成立的,意思无条件的成立,也就是说SQL语句中有没有这个1=1都可以。

这个1=1常用于应用程序根据用户选择项的不同拼凑where条件时用的。


如果不写1=1,那么在每一个不为空的查询条件面前,都必须判断有没有where字句,哪里该加where,哪里该加and/or

用上 where 1=1 之后,就不存在这样的问题, 条件是 and 就直接and ,是or就直接接 or


public function index()
{
$where = '1=1';
$searchArr = [];//记录搜索状态
if($this->request->isGet()){
$searchArr = $this->request->param();
unset($searchArr['page']);
foreach ($searchArr as $k=>$v) {
if($v != '' || $v != 0){
if($k == 'name'){
$where .= " and a.`{$k}` like '%{$v}%'";
}else if ($k== 'role_name'){
$where .= " and r.`name` like '%{$v}%'";
}else{
$where .= " and a.`{$k}` = '{$v}'";
}
}
}
}
}



__________________________________________________________________________________

若有帮助到您,欢迎点击推荐,您的支持是对我坚持最好的肯定(*^_^*)

你要保守你心,胜过保守一切。

作者:刘俊涛的博客​




举报

相关推荐

0 条评论