8

Is it possible to group and_where / or_where / or_like... statements together so as not to mix with other and/where statements.

Something that would result in

WHERE city = 'My City' AND state = 'My State' AND (name LIKE %name1% OR name LIKE %name2%)

kilrizzy
  • 2,895
  • 6
  • 40
  • 63

3 Answers3

18

I know this is a little late, but I found this post when looking into it and found a better solution than the one proposed by Sean.

$name = 'Bob';

$this->db->where('city', 'My City');
$this->db->where('state', 'My State');
$this->db->group_start();
    $this->db->like('name', $name);
    $this->db->or_like('name', $name);
$this->db->group_end();
arrowd
  • 33,231
  • 8
  • 79
  • 110
Ben
  • 199
  • 1
  • 7
14

Yes. $this->db->where() allows you to write clauses manually. You could do this:

$this->db->where('city', 'My City');
$this->db->where('state', 'My State');
$this->db->where('(name LIKE %name1% OR name LIKE %name2%)', null, false);

Setting the third parameter for false prevents CodeIgniter from trying to add backticks to the clause.

Check out the Active Record documentation. The section titled $this->db->where(); explains the four methods you can use to set WHERE clauses.

Sean Fahey
  • 1,850
  • 3
  • 26
  • 36
birderic
  • 3,745
  • 1
  • 23
  • 36
4

These two functions group_start() and group_end() have been implemented in CodeIgniter 3.0.3. Here is little better implementation according to the original question.

$name1 = 'Bob';
$name2 = 'John';

$this->db->where('city', 'My City');
$this->db->where('state', 'My State');
$this->db->group_start();
$this->db->like('name', $name1);
$this->db->or_like(('name', $name2);
$this->db->group_end();
Arafat
  • 61
  • 5