phpcodeigniteractiverecordwhere-clauselogical-grouping

How to construct a CodeIgniter active record query with a mix of OR and AND statements in the WHERE clause


I have recently begun converting my backend queries in my codeigniter application to active record pattern. As of now I am using codeigniter 2.1 version. I have originally written a query in mysql as

SELECT *
FROM table
WHERE (field1 = $field1 OR field2 = $field2)
    AND field3 = $field3
    AND field4 = 'text'

Now I would like to write this thing in a way given below:

$this->db->select('*');
$this->db->from('table');
$this->db->where('field1',$field1);
$this->db->or_where('field2',$field1);
$this->db->where('field3',$field2);
$this->db->where('field4','text');

But somehow the "or_where" function is not working properly.


Solution

  • you write custom string in Active Record

    $where = "(field1 = " . $field1 . " OR field2 = " . $field2 . ") AND 
              field3 = ". $field3 . " AND field4 = 'text'";
    $this->db->where($where);
    

    Click here for source: Active Record (and browse for custom string)