【问题标题】:PHP - Binding array of strings to IN() clause using PDOPHP - 使用 PDO 将字符串数组绑定到 IN() 子句
【发布时间】:2014-07-08 22:54:59
【问题描述】:

我正在努力将字符串数组绑定到 MySQL 语句中的 IN() 子句。我发现了很多关于整数的信息,但所有使用的方法都不适用于字符串。


这是我目前的代码:

$dbconnect = new PDO(...);

$brands = array('Nike', 'Adidas', 'Puma');
$i = 1;

try {
    $dbconnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);    
    $data = $dbconnect->prepare("SELECT * FROM clothing WHERE brand IN (:brands)");
    $data->bindParam(':brands', $brands);
    $data->execute();

        while($row = $data->fetch()) {
            echo $i++ . " - ". $row['brand'] . "<br>";
        }

    } catch(PDOException $er) {
        echo 'Error: ' . $er->getMessage();

}


提前感谢您的帮助!

【问题讨论】:

标签: php mysql pdo


【解决方案1】:

我喜欢循环并创建值的关联数组。然后将键连接到要绑定的参数字符串。然后遍历关联数组以将它们绑定到准备好的语句。以下内容(可能存在一些语法错误,但这是要点):

 $in_clause_array  = array();
 foreach($brands as $index => $brand) {
      $in_clause_array[':brand_'.$index] = $brand;
 } 

 //Below creates a string like ":brand_1 , :brand_2 , :brand_3"
 $in_clause_string = implode(" , ", array_keys($in_clause_array));

 $data = $dbconnect->prepare("SELECT * FROM clothing WHERE brand IN ( $in_clause_string )");

 //now bind the params to values in the associative array
 foreach($in_clause_array as $key=>$brand) {
         $data->bindValue("$key", $brand);
 }

【讨论】:

    【解决方案2】:
        $array_fields = array();
        $i=0;
        $res = $db->query("yourkey ".TABLE_ADS);
        while($row = mysql_fetch_row($res)) { 
            $array_fields[$i] = $row[0];
            $i++;
        }
    

    【讨论】:

      猜你喜欢
      • 2022-12-31
      • 1970-01-01
      • 1970-01-01
      • 2015-01-06
      • 2013-11-14
      • 2017-04-08
      相关资源
      最近更新 更多