combining mysql AND OR queries in Codeigniter

97,076

Solution 1

and this will work?

$this->db->where('LastName', 'Svendson');
$this->db->where('Age', 12);
$this->db->where("(FirstName='Tove' OR FirstName='Ola' OR Gender='M' OR Country='India')", NULL, FALSE);
$query = $this->db->get('Persons');
return $query->result();

Solution 2

In CodeIgniter 3 there are new methods group_start() and group_end() which serve exactly for this purpose.

return $this->db
     ->where('LastName', 'Svendson');
     ->where('Age', 12);
     ->group_start()
         ->where('FirstName','Tove')
         ->or_where('FirstName','Ola')
         ->or_where('Gender','M')
         ->or_where('Country','India')
     ->group_end()
     ->get('Persons')
     ->result();

Solution 3

using codeigniter 3.0 frame work,there is new feature available for separate or where and where operation.that is,group by and group end

code like,

$this->db->where('LastName', 'Svendson');
$this->db->where('Age', 12);
$this->db->group_start();
$this->db->or_where('FirstName','Tove');
$this->db->or_where('FirstName','Ola');
$this->db->or_where('Gender','M');
$this->db->or_where('Country','India');
$this->db->group_end();
$query = $this->db->get('Persons');
return $query->result();

Solution 4

In Codeigniter we can use like this it easy to understand.

$sql = "SELECT
            *
        FROM
            `Persons`
        WHERE
            LastName = 'Svendson'
        AND Age = '12'
        AND (
            FirstName = 'Tove'
            OR FirstName = 'Ola'
            OR Gender = 'M'
            OR Country = 'India'
        )";

$query = $this->db->query($sql);

return $query->result();

Solution 5

You can use this simply

$this->db->where("status","live")->or_where("status","dead");

you can also use

$this->db->where("(status='live' OR status='dead')");
Share:
97,076
gopi1410
Author by

gopi1410

Currently a Software Engineer in Samsung Research Institute Bangalore, India (SRI-B). Know more about me here. Check out my Careers 2.0 profile.

Updated on May 16, 2020

Comments

  • gopi1410
    gopi1410 about 4 years

    I want to combine AND OR mysql queries in CI. I have already seen this thread: http://codeigniter.com/forums/viewthread/92818/. But they don't provide the exact solution there.

    How do I create the following query using strictly the CI framework? (I can create the query easily without the brackets but then it is not the same query.)

    SELECT * FROM `Persons` WHERE
    LastName='Svendson' AND Age="12" AND
    (FirstName='Tove' OR FirstName='Ola' OR Gender="M" OR Country="India") 
    

    P.S.: This is just a sample query even if it makes no sense & Do not suggest writing the entire OR part of the query inside a single where().

    EDIT: Basically I want the implementation of the following simple query:

    SELECT * FROM `table` WHERE field1='value1' AND (field2='value2' OR field3='value3')