35

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

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

如果我删除通配符(%)然后搜索工作正常。$query 也只是带有用户输入的字符串。任何帮助表示赞赏。

4

7 回答 7

59

$this->db->like()自动添加 %s 并转义字符串。所以你只需要

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

请参阅 CI 文档以供参考:CI 2CI 3CI 4

于 2013-04-26T00:47:18.963 回答
21
  $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%'
于 2017-10-12T13:24:44.263 回答
12

对于完整的用户,您可以:

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

对于 %$query 你可以使用

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

对于 $query% 你可以使用

$this->db->like('title', $query, 'after');
于 2016-06-18T04:32:23.307 回答
6

$this->db->like()

此方法使您能够生成 LIKE 子句,这对进行搜索很有用。

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

产生:WHERE titleLIKE '%match%'

如果要控制通配符 (%) 的放置位置,可以使用可选的第三个参数。您的选项是“之前”、“之后”、“无”和“两者”(这是默认设置)。

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

产生:WHERE titleLIKE '%match'

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

产生:WHERE titleLIKE 'match%'

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

产生:title像“匹配”这样的地方

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

产生:WHERE titleLIKE '%match%'

于 2020-01-28T22:59:36.150 回答
2

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

$this->db->like('title', 'match', 'none'); 
// Produces: WHERE title LIKE 'match'
于 2014-06-30T11:22:47.163 回答
0

我在用着

$this->db->query("SELECT * FROM film WHERE film.title LIKE '%$query%'"); for such purposes
于 2013-04-26T00:34:29.603 回答
-2

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

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%");
}
于 2017-06-17T16:34:39.833 回答