My mistakes

Codeigniter grouping OR conditions using active record database library

Posted on: February 13, 2009

when someone trying to or two conditions using active record database library in codeigniter

Eg:

$this->db->from('posts');

$this->db->where('id', $id);

$this->db->like('title', $title);

$this->db->like('body', $body);
$this->db->or_like('author', $author);

You can do it like this

$this->db->from('posts');

$this->db->where('id', $id);
$this->db->where('(`title` LIKE \'%'.$title.'%\' OR `body` LIKE \'%'.$body.'%\' OR `author` LIKE \'%'.$author.'%\')', NULL, FALSE);

// Query:

// SELECT * FROM (`posts`) WHERE (`title` LIKE '%ach%' OR `text` LIKE '%ach%' OR `author` LIKE '%ach%') AND `id` = '12'


Advertisements

8 Responses to "Codeigniter grouping OR conditions using active record database library"

I’m sorry to tell you this but your solution is not elegant. You can, however, insert some lines of codes in DB_active_rec.php file ( [your_root]/system/database/ DB_active_rec.php). By concatenating ‘(‘ at the beginning of the or_where() or or_like() return string, then ‘)’ at the end, the problem is solved.

BTW, this is how I would recommend doing it to prevent sql injections since this is more than likely some sort of search method:

$str = ‘%’.$str.’%’;
$this->db->where(‘deleted’, NULL)
->where(sprintf(
‘(`content` LIKE %1$s OR `teaser` LIKE %1$s OR `title` LIKE %1$s)’,
$this->db->escape($str)
)
)
->order_by(‘sort’)
->order_by(‘added’, ‘desc’);

thanks man 🙂

Thanks..
Its very helpful

very helpful,thanks

thanks, very useful

Thanks!! $this->db->or_like sometimes goes “and … like …” Ergh..

thanks ,its done it correctly

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: