我在codeigniter中有简单的数据库查询,但是我无法让搜索与通配符一起工作。这是我的代码:Codeigniter喜欢与通配符(%)
$this->db->like('film.title',"%$query%");
$this->db->escape_like_str($query);
$res = $this->db->get('film');
如果我删除通配符(%),然后搜索工作正常。另外$查询只是用户输入的字符串。任何帮助表示赞赏。
我在codeigniter中有简单的数据库查询,但是我无法让搜索与通配符一起工作。这是我的代码:Codeigniter喜欢与通配符(%)
$this->db->like('film.title',"%$query%");
$this->db->escape_like_str($query);
$res = $this->db->get('film');
如果我删除通配符(%),然后搜索工作正常。另外$查询只是用户输入的字符串。任何帮助表示赞赏。
$this->db->like()
自动添加%s和逃逸的字符串。因此,所有你需要的是
$this->db->like('title', $query);
$res = $this->db->get('film');
参考见CI的文档Active Record Class (CI 2)或Query Builder Class (CI 3)。
它不这样工作。如果我搜索让我们说死硬,这发现它,因为标题匹配。如果我只是使用Die或Hard,没有发现任何东西。如果我使用带有字符串值的SQL,它可以正常工作。 – 2013-04-26 00:54:42
我的不好我在程序中有进一步的错误。 – 2013-04-26 01:03:11
对于'%$ query',你可以使用'$ this-> db-> like('title',$ query,'before')'和'$ query%',你可以使用'$ this-> db->就像在答案中的链接所说的那样('标题',$查询,'之后')'。 – Mehmed 2013-10-24 07:53:24
如果你不想使用通配符(%),你可以传递给可选的第三个参数'none'。
$this->db->like('title', 'match', 'none');
// Produces: WHERE title LIKE 'match'
皮草全部喜欢,你可以用户:
$this->db->like('title',$query);
对于%$查询,你可以使用
$this->db->like('title', $query, 'before');
和$查询%可以使用
$this->db->like('title', $query, 'after');
一次搜索多个字段可以像这样完成...
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%");
}
$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%'
尝试没有$这个 - > DB-> escape_like_str($查询); – Spec 2013-04-26 00:42:50
但不要忘记$ this-> db-> like('film.title',$ query,before);是一个非常昂贵的搜索,因为mysql不能为此使用索引。更好地使用全文索引 – Michael 2016-07-05 21:39:41