对数组中的每个项目运行 SQL 查询的最佳方法是什么?
我有$array代码:
Array
(
[0] => 12345
[1] => 12346
[3] => 12347
)
现在我想对 $array 中的每个项目运行以下 SQL 查询:
SELECT * FROM `TABLE` a WHERE a.`Code` = :code
我一直在使用的 PHP:
$results = array();
$statement = $pdo->prepare($sql);
$statement->bindParam(':code', $value);
foreach ($array as $key => $value) {
$statement->execute();
while (($results = $statement->fetch(PDO::FETCH_ASSOC)) !== false) {
echo $results;
}
}
最佳答案
您可以运行一个查询,然后循环结果,而不是运行多个查询:
SELECT * FROM `TABLE` a WHERE a.`Code` IN (:codes);
在你的 PHP 中这将是这样的:
$question_marks = str_repeat("?,", count($array_of_codes)-1) . "?";
$statement = $pdo->prepare($sql);
$statement->bindParam(:codes, $question_marks);
$statement->execute($array_of_codes);
while (($results = $statement->fetch(PDO::FETCH_ASSOC)) !== FALSE) {
echo $results;
}
其中 $array_of_codes
是 PHP 数组,其中包含您要查找的每个结果的 Code
参数。
应得的信用 This question帮助了解如何使用 PDO 执行 WHERE...IN 查询。
关于PHP 有效地重复 SQL 查询每个数组的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36118134/