combining mysql AND OR queries in Codeigniter

前端 未结 9 1470
慢半拍i
慢半拍i 2020-12-09 07:35

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 th

相关标签:
9条回答
  • 2020-12-09 08:32

    I needed this for CodeIgniter 2, but I needed the values still escaped so csotelo's answer wasn't good for me and I didn't want to rewrite the whole query like Shawn C's answer, so I ended up doing this:

    $this->db->where('LastName', $lastName);
    $this->db->where('Age', $age, false);
    $this->db->where('1 AND ( 0', null, false); // This one starts the group
      $this->db->or_where('FirstName', $firstName1);
      $this->db->or_where('FirstName', $firstName2);
      $this->db->or_where('Gender', $gender);
      $this->db->or_where('Country', $country);
    $this->db->or_where('0 )', null, false); // This one ends the group
    $query = $this->db->get('Persons');
    

    Which generates the following query:

    SELECT *
    FROM (`Persons`)
    WHERE `LastName` =  'Svendson'
    AND Age = 12
    AND 1 AND ( 0 -- This one starts the group
    OR `FirstName` =  'Tove'
    OR `FirstName` =  'Ola'
    OR `Gender` =  'M'
    OR `Country` =  'India'
    OR 0 ) -- This one ends the group
    

    Which would be the same as this:

    SELECT * FROM (`Persons`) WHERE
    `LastName` = 'Svendson' AND Age = 12 AND 1 AND
    (0 OR `FirstName` = 'Tove' OR `FirstName` = 'Ola' OR `Gender` = 'M' OR `Country` = 'India' OR 0)
    
    0 讨论(0)
  • 2020-12-09 08:36

    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();
    
    0 讨论(0)
  • 2020-12-09 08:36

    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();
    
    0 讨论(0)
提交回复
热议问题