Codeigniter parentheses in dynamic Active Record query
One of best feature to save your query when you applying multiple where or_where clauses.
$this->db->group_start();
$this->db->where();
$this->db->or_where();
$this->db->group_end();
Happy Coding. :)
In the CI 3.0-dev you can add groups in query:
$this->db->select('id, title')
->group_start()
->or_like([ 'title' => $s, 'id' => $s ])
->group_end()
->where([ 'b_del' => 0 ]);
Produces:
SELECT `id`, `title`, `venda1`
FROM `itens`
WHERE
(
`title` LIKE '%a%' ESCAPE '!'
OR `id` LIKE '%a%' ESCAPE '!'
)
AND `b_del` =0
From the CI wiki:
The codeignighter ActiveRecord feature allows you to create SQL queries relatively simply and database-independant, however there isno specific support for including parenthesis in an SQL query.
For example when you want a where statement to come out simmilarly to the folowing:
WHERE (field1 = value || field2 = value) AND (field3 = value2 || field4 = value2)
This can be worked around by feeding a string to the CI->db->where() function, in this case you will want to specifically escape your values.
See the following example:
$value=$this->db->escape($value);
$value2=$this->db->escape($value2);
$this->db->from('sometable');
$this->db->where("($field = $value || $field2 = $value)");
$this->db->where("($field3 = $value2 || $field4 = $value2)");
$this->db->get();
A simmilar workaround can be used for LIKE clauses:
$this->db->where("($field LIKE '%$value%' || $field2 LIKE '%$value%')");
$this->db->where("($field3 LIKE '%$value2%' || $field4 LIKE '%$value2%')");