0
votes

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

Any help or suggestion would be a great help.

See updated question here: join not giving required result when using or_like codeigniter

2
$array_like is already an array because of explode(), perhaps changing your $this->db->like('topic',array($array_like)); to $this->db->like('topic',$array_like); might be a good start. - missing_one
@dqlopez i have tried but again array to strign converstion notice is coming - Mohammed Sufian

2 Answers

7
votes

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);
0
votes

Assuming you are using Codeigniter 2.1.4, as you can read in CodeIgniter active record documentation, you cannot pass the second argument as array in like function. You need to pass a string as argument.

$array_string = "smart,intelligent,awesome";
$array_like = explode(',', $array_string);

foreach ($array_like as $like)
{
    $this->db->like('topic', $like);
}