php - CodeIgniter "like()" function with % wildcard inside search terms -
let's have function this:
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(); }
produce query :
select * table_name foo_column '%match something%'
as can see %
wildcard can added in both side, before
, after
.
and how if want produce like:
... foo_column '%match%something%'?
fyi, use str_replace()
function change space
%
codeigniter escape
slash
. produces query like:
... foo_column '%match\%something%'
this useful when search match something keyword match something, , wildcard
on first and/or after seems doesn't work.
in order achieve such kind of functionality i've updated code different conditions like.
note: here i've manually placed values of categories , 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 $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(); }
here $search = 'match something'
, this'll generate query follows:
select * (`table_name`) `category` = 'electronics' , `foo_column` '%match%' or `foo_column` '%something%' limit 10
if $search = 'match another'
it'll generate query as
select * (`table_name`) `category` = 'electronics' , `foo_column` '%match%' or `foo_column` '%something%' or `foo_column` '%another%' limit 10
and if $search = 'match'
it'll generate query as
select * (`table_name`) `category` = 'electronics' , `foo_column` '%match%' limit 10
and if $search = ''
it'll generate query as
select * (`table_name`) `category` = 'electronics' limit 10
Comments
Post a Comment