这是我拥有的代码的简化版本:
$this->db->select('column1, column2, status, etc');
if ($search['option_1']){
$this->db->or_where('status', 15);
$this->db->or_where('status', 20);
}
if ($search['option_2']){
$this->db->or_where('status', 30);
$this->db->or_where('status', 40);
$this->db->or_where('status', 50);
}
if ($search['option_3']){
$this->db->or_where('status', 99);
}
$this->db->where('column', $search['value']);
etc..
在网页(搜索表单(上,除了其他字段和选择框外,我还有三个复选框:option_1到option_3。所有复选框都是可选的。每个复选框对应一个状态。
复选框可以全部选中、部分选中或不选中。
我认为这段代码的问题在于OR语句周围缺少括号,因此"打断"了查询。我必须制作:吗
if ($search['option_1']){
$this->db->where('(status = 15 OR status = 20)');
}
if ($search['option_1'] && $search['option_2']){
$this->db->where('(status = 15 OR status = 20 OR status = 30 OR status = 40 OR status = 50)');
}
etc...
或者有更聪明的方法吗?
[更新]
我一直在使用这个,直到有人想出更好的方法:
if($search['option_1'] || $search['option_2'] || $search['option_3']) {
if ($search['option_1']){
$status = '(status = 15 OR status = 20)';
}
else if ($search['option_2']){
$status = '(status = 30 OR status = 40 OR status = 50)';
}
else if($search['option_3']) {
$status = 'hr_olas.k_VALU_Status = 99';
}
else if($search['option_1'] && $search['option_2']) {
$status = '(status = 15 OR status = 20 OR status = 30 OR status = 40 OR status = 50)';
}
else if($search['option_1'] && $search['option_3']) {
$status = '(status = 15 OR status = 20 OR status = 99)';
}
else if($search['option_2'] && $search['option_3']) {
$status = '(status = 30 OR status = 40 OR status = 50 OR status = 99)';
}
else if($search['option_1'] && $search['option_2'] && $search['option_3']) {
$status = '(status = 15 OR status = 20 OR status = 30 OR status = 40 OR status = 50 OR status = 99)';
}
$this->db->where($status);
}
好的方法是(状态IN(15,20((,
但是要调试你的问题,请打印出查询,看看的问题
echo $this->db->last_query();
假设如下:
if ($search['option_1']){
$this->db->select('column1, column2, status, etc');
$this->db->or_where('status', 15);
$this->db->or_where('status', 20);
$this->db->where('column', $search['value']);
etc
$query = $this->db->get();
}
if ($search['option_2']){
$this->db->select('column1, column2, status, etc');
$this->db->where('column', $search['value']);
$this->db->or_where('status', 30);
$this->db->or_where('status', 40);
$this->db->or_where('status', 50);
etc
$query = $this->db->get();
}
if ($search['option_3']){
$this->db->select('column1, column2, status, etc');
$this->db->where('column', $search['value']);
$this->db->or_where('status', 99);
etc
$query = $this->db->get();
}
$this->db->select('column1, column2, status, etc');
$this->db->where('column', $search['value']);
if ($search['option_1']){
$this->db->or_where(array('status'=>'15','status'=>20));
}
if ($search['option_2']){
$this->db->or_where(array('status'=>'30','status'=>'40','status'=>'50'));
}
if ($search['option_3']){
$this->db->or_where(array('status'=>'99'));
}
$query = $this->db->get();
希望,这将有所帮助。。。