Like Query in Codeigniter

This tutorial shows you how to write like query in codeigniter. Like clause is used in ‘SELECT Query’ to search for the matching pattern in columns. The operator is part of the where clause and employs wildcard character (%) to search for the matching string.

Let’s create a like method in codeigniter

$this->db->like('title', 'php');
// Produces: WHERE `title` LIKE '%php%' ESCAPE '!'

If you use multiple method calls they will be chained together with AND between them

$this->db->like('title', 'php');
$this->db->like('body', 'article');
// WHERE `title` LIKE '%php%' ESCAPE '!' AND  `body` LIKE '%article% ESCAPE '!'

If you want to control where the wildcard (%) is placed, you can use an optional third argument.

$this->db->like('title', 'match', 'before');    // Produces: WHERE `title` LIKE '%match' ESCAPE '!'
$this->db->like('title', 'match', 'after');     // Produces: WHERE `title` LIKE 'match%' ESCAPE '!'
$this->db->like('title', 'match', 'both');      // Produces: WHERE `title` LIKE '%match%' ESCAPE '!'

Array method with like query

$array = array('title' => $match, 'page1' => $match, 'page2' => $match);
$this->db->like($array);
// WHERE `title` LIKE '%match%' ESCAPE '!' AND  `page1` LIKE '%match%' ESCAPE '!' AND  `page2` LIKE '%match%' ESCAPE '!'

Leave a Reply

Your email address will not be published. Required fields are marked *