PDO IN() Array Statement AND a placeholder

前端 未结 5 869
死守一世寂寞
死守一世寂寞 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:03

    Placeholders version if you need it

    $values = [1, 4, 7, 8];
    $placeholders =  preg_filter('/^/', ':prefix_', array_keys($values)));
    $query = 'SELECT * FROM table WHERE id IN ( '. implode(', ', $placeholders) . ')';
    
    $stmt = $db->prepare($query);
    
    if (count($values) > 0) {
        foreach ($values as $key => $current_value) {
            $stmt->bindValue($placeholders[$key] , $current_value, PDO::PARAM_STR);
        }
    }
    
    $stmt->execute();
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    

提交回复
热议问题