Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter LIKE with wildcard(%)

I have simple database query in codeigniter, however I cannot get search to work with wildcard. This is my code:

$this->db->like('film.title',"%$query%");
$this->db->escape_like_str($query);
$res = $this->db->get('film');

If I remove wildcard(%) then search works fine. Also $query is just string with user input. Any help is appreciated.

like image 710
James Douglas Avatar asked Apr 26 '13 00:04

James Douglas


4 Answers

$this->db->like() automatically adds the %s and escapes the string. So all you need is

$this->db->like('title', $query);
$res = $this->db->get('film');

See the CI documentation for reference: CI 2, CI 3, CI 4

like image 114
Samutz Avatar answered Nov 18 '22 06:11

Samutz


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

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

$this->db->like('title', 'match', 'both'); 
// Produces: WHERE title LIKE '%match%'
like image 22
Bijendra Ch Avatar answered Nov 18 '22 06:11

Bijendra Ch


For Full like you can user :

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

For %$query you can use

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

and for $query% you can use

$this->db->like('title', $query, 'after');
like image 12
NIMESH PAREKH Avatar answered Nov 18 '22 07:11

NIMESH PAREKH


$this->db->like()

This method enables you to generate LIKE clauses, useful for doing searches.

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

Produces: WHERE title LIKE '%match%'

If you want to control where the wildcard (%) is placed, you can use an optional third argument. Your options are ‘before’, ‘after’, ‘none’ and ‘both’ (which is the default).

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

Produces: WHERE title LIKE '%match'

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

Produces: WHERE title LIKE 'match%'

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

Produces: WHERE title LIKE 'match'

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

Produces: WHERE title LIKE '%match%'

like image 6
symi khan Avatar answered Nov 18 '22 06:11

symi khan