我正在努力将一个字符串数组绑定到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();
}
在此先感谢您的帮助!
答案 0 :(得分:0)
我喜欢循环并创建值的关联数组。然后将键连接到一串要绑定的参数。然后遍历关联数组以将它们绑定到预准备语句。以下内容(可能存在一些语法错误,但这是要点):
$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);
}
答案 1 :(得分:-1)
$array_fields = array();
$i=0;
$res = $db->query("yourkey ".TABLE_ADS);
while($row = mysql_fetch_row($res)) {
$array_fields[$i] = $row[0];
$i++;
}