PDO IN() Array Statement AND a placeholder

前端 未结 5 867
死守一世寂寞
死守一世寂寞 2021-01-04 08:16

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         


        
5条回答
  •  隐瞒了意图╮
    2021-01-04 09:14

    $stm->execute($values,$product) ; //error happens when adding product placeholder
    

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

    We already have a perfectly good $values array, so let's reuse it after you create 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);
    

提交回复
热议问题