php-CodeIgniter“ like()”函数,在搜索词中包含%通配符
作者:互联网
假设我有这样的功能:
public function get_list($category = '', $limit = 10, $offset = 0) {
if (!empty($category))
$this->db->where('category', $category);
$search = $this->input->get('search');
if (!empty($search))
$this->db->or_like(array('foo_column'=>$search));
$query = $this->db->get('table_name', $limit, $offset);
//echo $this->db->last_query();
return $query->result();
}
产生查询为:
SELECT * FROM table_name WHERE foo_column LIKE '%match something%'
如您所见,%通配符可以在前后添加.
以及如果我想产生像:
... WHERE foo_column LIKE '%match%something%'?
仅供参考,我使用str_replace()函数将空间更改为%,但codeigniter始终使用斜杠对其进行转义.
它产生如下查询:
... WHERE foo_column LIKE '%match\%something%'
当搜索匹配另一个匹配项和关键字匹配匹配项,并且在第一个和/或之后的通配符似乎不起作用时,这很有用.
解决方法:
为了实现这种功能,我使用了一些不同的条件来更新您的代码.
Note: Here I’ve manually placed values of categories and search
public function get_list($category = '', $limit = 10, $offset = 0) {
$category = 'electronics';
if (!empty($category)) {
$this->db->where('category', $category);
}
$search = 'match something';
if (preg_match('/\s/', $search) > 0) {
$search = array_map('trim', array_filter(explode(' ', $search)));
foreach ($search as $key => $value) {
$this->db->or_like('foo_column', $value);
}
} else if ($search != ''){
$this->db->like('foo_column', $search);
}
$query = $this->db->get('table_name', $limit, $offset);
return $query->result();
}
在这里$search =’match something’,这将生成查询,如下所示:
SELECT * FROM (`table_name`) WHERE `category` = 'electronics' AND
`foo_column` LIKE '%match%' OR `foo_column` LIKE '%something%' LIMIT 10
如果$search =’匹配其他东西’,它将生成查询为
SELECT * FROM (`table_name`) WHERE `category` = 'electronics' AND
`foo_column` LIKE '%match%' OR `foo_column` LIKE '%something%' OR
`foo_column` LIKE '%another%' LIMIT 10
并且如果$search =’match’它将生成查询为
SELECT * FROM (`table_name`) WHERE `category` = 'electronics' AND
`foo_column` LIKE '%match%' LIMIT 10
并且如果$search =”它将生成查询为
SELECT * FROM (`table_name`) WHERE `category` = 'electronics' LIMIT 10
标签:query-builder,codeigniter,mysql,php 来源: https://codeday.me/bug/20191120/2043083.html