Part of the EllisLab Network
x
 
Create New Page
 View Previous Changes    ( Last updated by norgus )

Category:Libraries:ActiveRecord:Including Parenthesis

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%')"); 

This wiki article may seem obvious to some, but I’ve seen the question posed in the forums more than once, and untill I realised this method was available I was building the string with the ActiveRecord class, returning it, doing some nasty preg_replace() on the string and then putting it straight back into CI->db->query() which is probably a workaround best avoided.

Articles in category "Libraries:ActiveRecord:Including Parenthesis":

There is 1 article for this category