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粉2168079242023-10-24 17:57:03
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粉5010077682023-10-24 09:30:01
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)));
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