简体   繁体   中英

PDO Select query using array of OR

I have an array of objects:

$arr = array('10', '12');

and i am running this query using PDO:

$stmt = $pdo->prepare("SELECT * from table WHERE user_sequence = :user_sequence");

i want to be able to have the query say WHERE user_sequence = :item1 OR user_sequence = :item2

item1, item2 etc being the objects from the array

how can i do this using PDO?

usually in MySQL, i would do:

$sql="SELECT * from table WHERE ";
foreach($array as $a) {
    $sql.="col = '".$a."' OR ";
}

but im not sure how to copy this theory in a PDO query

You could do it like this:

$values = [ 'first value', 'second value', 'third value' ];

$conds = array_map(function() {
    return "user_sequence = ?";
}, $values);

$sql = "SELECT * from table WHERE " . implode(" OR ", $conds);

$stmt = $pdo->prepare($sql);
$stmt->execute($values);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM