Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO IN() Array Statement AND a placeholder

I found this code on SO, which is great for using PDO and the IN() statement 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) ;

However, how can I mix in another addition to the query so the query 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 parameter number: number of bound variables does not match number of tokens in line 3 (the $stm line)

Any idea how to get this to behave as intended?

UPDATED execute to array, still not working..

like image 801
Maverick Avatar asked Jan 24 '12 17:01

Maverick


1 Answers

Solution

This should work, if $values is an array:

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

Explanation

execute() expects one parameter - in this case an array - to be provided. By adding array_merge($values, array($product)) you create one array with $product added at the end, so the query should work correctly.

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

like image 86
Tadeck Avatar answered Oct 14 '22 20:10

Tadeck