4

I am using db_select for database query, following code works fine when $keyword is any string

 $result = db_select('my_table', 'mt')
        ->fields('mt')
        ->condition('my_column', '%' . db_like($keyword) . '%', 'LIKE')
        ->execute()
        ->fetchAllKeyed();

How can I make the same query working when $keyword is suppose to be an array of strings like ("del","mum") ,if my_column is location column so query will return me places like Delhi, Mumbai.

1
9

You can build your query while looping through each keyword and adding this as an OR condition.

$db_or = db_or();
$query = db_select('my_table', 'mt');
$query->fields('mt');

foreach ($keywords as $keyword) {
    $db_or->condition('my_column', '%' . db_like($keyword) . '%', 'LIKE');
}

$query->condition($db_or);
$results = $query->execute()->fetchAllKeyed();
1
  • Thanks! syntax error at $db_or->condition('my_column', '%' . db_like($keyword) . '%', 'LIKE')); extra ')' at the end. – Prashant Kanse Mar 26 '17 at 17:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.