1
votes

I have a function returning data based on the parameters passed. Basically, the queries change depending on the clauses.

if(1==$case) 
return select()->from('db')->where('x',$something)->where('y','fixed')...

else if(2==$case)
return select()->from('db')->where('x','fixed')->where('y',$something)...

Is there a better way of doing this?

Also, is it possible to have such a clause

...->where('category',*)

'*' to be replaced by a value or something which equates to "any".

3

3 Answers

3
votes

This type of queries is also called "dynamic queries" because you can combine the clauses in an easy way. Try this:

$query = $this->db->select()
    ->from('db');
if(1==$case) {
    $query->where('x',$something)
          ->where('y','fixed')
}
elseif (2==$case){
    $query->where('x','fixed')
          ->where('y',$something)
}
....
return $query->get();

Answering your second question, you can use:

$this->db->like('category', '%');
3
votes

You can do like this-

$where = array();

if(1==$case) 
 $where['x'] = $something;
 $where['y'] = 'fixed';

else if(2==$case)
 $where['x'] = $something;
 $where['y'] = 'fixed';

$this->db->where($where);
$this->db->get();
1
votes

You could have simplified it like this

if($case == 1){
    $this->db->where('x',$something)->where('y','fixed');
}else if($case == 2){
    $this->db->where('x','fixed')->where('y',$something)
}else{
    //no where clause
}
$query  =   $this->db->get('db_table');
return $query->result();