search

Home  >  Q&A  >  body text

PDO IN() array statement AND placeholder

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粉832490510P粉832490510461 days ago688

reply all(2)I'll reply

  • P粉216807924

    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);

    reply
    0
  • P粉501007768

    P粉5010077682023-10-24 09:30:01

    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

    reply
    0
  • Cancelreply