phpcodeigniteractiverecordcodeigniter-3query-builder

CodeIgniter query WHERE clause with enclosed OR LIKE conditions and other non-LIKE conditions


I want to convert the following SQL query to codeIgniter active records format

SELECT * FROM `relation`
WHERE (`user1` = 144 OR `user2` = 144)
AND `status` = 2
AND `action` != 1

My attempt was something like this,

$ID = 144;
$this->db->where('user1', $ID);
$this->db->or_where('user2', $ID);
$this->db->where('status', 2);
$this->db->where('action!=', 1);

However the results are not compatible. Can you point what is off here?

I would also be fine with suggestions not specifically using active records for the query.


Solution

  • As your are using OR between multiple condition you must have to enclosed this in bracket. Change your code as below:

    $this->db->where('(user1', $ID,FALSE);
    $this->db->or_where("user2 = $ID)",NULL,FALSE);
    $this->db->where('status', 2);
    $this->db->where('action!=', 1);