StuBlackett
StuBlackett

Reputation: 3857

Active Record WHERE Query not getting a field

I am trying a "Keyword" search. I am looking in the fields ARTWORK_title and ARTWORK_keywords. The ARTWORK_keywords field is where the user can enter multiple tags to search on.

I have built a query up and feel this is the right way, But I am just not getting ARTWORK_title passed back through in the DB Query.

My PHP Function is as follows....

$my_keywords = explode(",", $search_string);

    $searchfields = array('ARTWORK_title', 'ARTWORK_keywords');

    $this->db->select('*');
    $this->db->from('artwork');
    $this->db->where('ARTWORK_status', '1');

    //$where_string = '(';

    foreach($my_keywords as $keyword)
    {
        foreach($searchfields as $field)
        {
            $where_string = $field . ' LIKE \'%' . $keyword . '%\' ';
        }


        //$where_string .= substr($where_string, 4) . ')';

        $this->db->where($where_string);
}

However when profiling the SQL Query I am getting the following MySQL Query back....

SELECT * FROM (artwork) WHERE ARTWORK_status = '1' AND ARTWORK_keywords LIKE '%Blue%' AND ARTWORK_keywords LIKE '%Orange%'

It is just not getting the ARTWORK_title field in the query at all.

Any ideas where I am going wrong?

Many Thanks in advance.

Upvotes: 0

Views: 82

Answers (1)

Yan Berk
Yan Berk

Reputation: 14428

You are erasing the $where_string value with each iteration.

Modify it like this:

$where_string = '';    
$counter = 0;
foreach($my_keywords as $keyword)
{
    foreach($searchfields as $field)
    {
        if ($counter > 0) {
           $where_string .= ' AND ';    
        }
        $where_string .= $field . ' LIKE \'%' . $keyword . '%\' ';
        $counter++;
    }
}

Upvotes: 1

Related Questions