PDO IN() array statement AND placeholder
P粉832490510
P粉832490510 2023-10-23 21:43:13
0
2
656

I found this code on SO which is great for using PDO and IN() statements together.

$values = explode(',', $values) ; # 1,4,7

$placeholders = rtrim(str_repeat('?, ', count($values)), ', ') ;
$query = "SELECT * FROM table WHERE id IN ($placeholders)";

$stm = $db->prepare($query) ;
$stm->execute($values) ;

But how do I mix other things into the query so that it looks like this:

$query = "SELECT * FROM table WHERE id IN ($placeholders) AND product=?";
$stm = $db->prepare($query) ;
$stm->execute(array($values,$product)) ; //error happens when adding product placeholder

I thought this would work but I get:

Warning: PDOStatement::execute() [pdostatement.execute]: SQLSTATE[HY093]: Invalid number of arguments: The number of bind variables does not match the number of tags in line 3 ($stm line )

Any idea how to make it work as expected?

Update is executed to the array, still does not work..

P粉832490510
P粉832490510

reply all(2)
P粉216807924

The problem here is that execute requires a single array. You can't pass multiple arrays, and worse, you can't nest arrays.

We already have a perfect $values array, so let's reuse it after creating the placeholder string.

$values = explode(',', $values) ; # 1,4,7

$placeholders = rtrim(str_repeat('?, ', count($values)), ', ') ;
$query = "SELECT * FROM table WHERE id IN ($placeholders) AND product=?";

// New!
$values[] = $product;

$stm = $db->prepare($query);
$stm->execute($values);
P粉501007768

solution

If $values is an array, this should work:

$query = "SELECT * FROM table WHERE id IN ($placeholders) AND product=?";
$stm->execute(array_merge($values, array($product)));

illustrate

execute() Requires a parameter (in this case an array). By adding array_merge($values, array($product)) you create an array and add $product at the end so the query should work fine.

View the demo here: http://ideone.com/RcClX

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template