PHP - Using PDO with IN clause array

前端 未结 8 1700
失恋的感觉
失恋的感觉 2020-11-21 06:03

I\'m using PDO to execute a statement with an IN clause that uses an array for its values:

$in_array = array(1, 2, 3);
$in_values = implode(\',\'         


        
8条回答
  •  Happy的楠姐
    2020-11-21 06:46

    An alternative version of PHP Delusions (@your-common-sense) using closures:

    $filter      = ["min_price" => "1.98"];
    $editions    = [1,2,10];
    
    $editions = array_combine(
        array_map(function($i){ return ':id'.$i; }, array_keys($editions)),
        $editions
    );
    $in_placeholders = implode(',', array_keys($editions));
    $sql = "SELECT * FROM books WHERE price >= :min_price AND edition IN ($in_placeholders)";
    $stm = $pdo->prepare($sql);
    $stm->execute(array_merge($filter,$editions));
    $data = $stm->fetchAll();
    

提交回复
热议问题