I would like to pass array to like
clause of active record in CodeIgnter for that I have written the following:
$array_string = 'smart,intelligent,awesome';
$array_like = explode(',',$array_string);
and in model:
$this->db->like('topic',array($array_like));
but I am getting
Severity: Notice
Message: Array to string conversion
See my related question here: CodeIgniter active record query where a column value is LIKE a value in a dynamic list
You can't just pass an array to the like()
function, it has to be a string. You need to apply a like
clause for each of the keywords in the string.
You need to use or_like
to match a record to either of the keywords, however, because if you just use like()
each time, it will need to match all of the keywords due to the query being like LIKE "%smart" AND LIKE "%intelligent"
etc. and that isn't what you require.
$array_string = "smart,intelligent,awesome";
$array_like = explode(',', $array_string);
foreach($array_like as $key => $value) {
if($key == 0) {
$this->db->like('topic', $value);
} else {
$this->db->or_like('topic', $value);
}
}
Try this way to avoid your problem of the rest of the where
statement being ignored.
$array_string = "smart,intelligent,awesome";
$array_like = explode(',', $array_string);
$like_statements = array();
foreach($array_like as $value) {
$like_statements[] = "topic LIKE '%" . $value . "%'";
}
$like_string = "(" . implode(' OR ', $like_statements) . ")";
The value of $like_string
will be (topic LIKE '%smart%' OR topic LIKE '%intelligent%' OR topic LIKE '%awesome%')
You can then use $like_string
in the following way with ActiveRecord:
$this->db->where($like_string, FALSE);