PHP 有效地为每个数组的项目重复 SQL 查询


PHP repeating SQL queries for each array's item efficiently

对数组中的每个项目运行SQL查询的最佳方法是什么?

我有代码$array

Array
(
  [0] => 12345
  [1] => 12346
  [3] => 12347
)

现在,我想为$array中的每个项目运行以下 SQL 查询:

SELECT * FROM `TABLE` a WHERE a.`Code` = :code

我一直在使用:

$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 参数。

信用到期 这个问题有助于如何做 在哪里...使用 PDO 进行查询。