112233
112233

Reputation: 2466

How to search through multiple columns in mysql

This is part of the query where it supposed to search through morning, afternoon and evening columns in posts table.

$add_here .= " AND posts.".$col." IN ('" . implode("',' ",$days) . "')";

$col is the variable that holds array or single value for column name supplied by user. Namely 'morning','afternoon','evening'. Do you know how to alter the query above to search in the array($col)?

The below works because I specified column name which is 'afternoon'. I wonder how to replace the text 'afternoon' with array of values!

 $add_here .= " AND posts.afternoon  IN ('" . implode("',' ",$days) . "')";

Upvotes: 0

Views: 50

Answers (1)

Amarnasan
Amarnasan

Reputation: 15579

Use array_map to build a series of conditions grouped with OR :

$days = ['sun','mon','tue'];
$col = ['afternoon','morning','night'];
$add_here = '';

$add_here .= sprintf(" AND (%s)",
    implode(' OR ', array_map(
            function($colx) use ($days) {
                return sprintf("posts.%s IN ('%s')", $colx, implode("','",$days));
            }, is_array($col) ? $col : array($col))
    )
);

AND (posts.afternoon IN ('sun','mon','tue') OR posts.morning IN ('sun','mon','tue') OR posts.night IN ('sun','mon','tue'))

Upvotes: 1

Related Questions