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..
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.solution
If
$values
is an array, this should work:illustrate
execute()
Requires a parameter (in this case an array). By addingarray_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