Codeigniter LIKE with wildcard(%)

爷,独闯天下 提交于 2020-01-22 06:44:47

问题


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.


回答1:


$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 Active Record Class (CI 2) or Query Builder Class (CI 3) in CI's docs for reference.




回答2:


Fur 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');



回答3:


  $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%'



回答4:


If you do not want to use the wildcard (%) you can pass to the optional third argument the option 'none'.

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



回答5:


I'm using

$this->db->query("SELECT * FROM film WHERE film.title LIKE '%$query%'"); for such purposes



回答6:


Searching multiple fields at once can be done like so...

function search($search)
{
    $sql = "SELECT * FROM some_table
    WHERE UPPER(a_name) LIKE ?
    OR
    UPPER(a_full_name) LIKE ?
    OR
    UPPER(a_city) LIKE ?
    OR
    UPPER(a_code) LIKE ?
    ";
    $arr = array_map(array($this,"wrapLIKE"),array($search, $search, $search, $search));
    $r = $this->db->query($sql, $arr);
    return $r;
}

function wrapLIKE($string)
{
    return strtoupper("%$string%");
}


来源:https://stackoverflow.com/questions/16226906/codeigniter-like-with-wildcard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!