带有通配符的Codeigniter LIKE(%)

niwlg2el  于 2022-12-06  发布在  其他
关注(0)|答案(7)|浏览(103)

我在codeigniter中有简单的数据库查询,但是我不能用通配符进行搜索。这是我的代码:

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

如果我删除通配符(%),那么搜索工作正常。而且$query只是用户输入的字符串。任何帮助都是感激的。

exdqitrt

exdqitrt1#

$this->db->like()会自动添加%s并转义字符串。因此,您所需要的是

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

请参阅CI文档以获取参考:CI 2,配置项3,配置项4

ctzwtxfj

ctzwtxfj2#

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

camsedfj3#

对于Full like,您可以使用:

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

对于%$query,您可以使用

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

对于$query%,您可以使用

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

vptzau2j4#

$this->db->like()
此方法使您能够生成LIKE子句,这对执行搜索很有用。
$this->db->like('title', 'match');

产生:WHERE title LIKE '%匹配%'

如果要控制通配符(%)的位置,可以使用可选的第三个参数。选项包括“before”、“after”、“none”和“both”(默认值)。
$this->db->like('title', 'match', 'before');

产生:WHERE title LIKE '%匹配'

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

产生:WHERE title LIKE '匹配%'

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

产生:WHERE title LIKE '匹配'

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

产生:WHERE title LIKE '%匹配%'

lb3vh1jj

lb3vh1jj5#

如果不想使用通配符(%),可以将选项“none”传递给可选的第三个参数。

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

nvbavucw6#

我在用

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

bzzcjhmw7#

一次搜索多个字段可以这样做...

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

相关问题