MySQLi查询以循环遍历数组并更新多行

2022-02-21 00:00:00 php mysqli

我有一个如下所示的数组:

$postdata[1] = 'This';
$postdata[2] = 'That';
$postdata[3] = 'The other';

,我想遍历数组并更新ID对应于数组键的所有行。点赞:

foreach ($postdata as $key => $value) {
  if ($key == 1) {
    $update = $db->query("UPDATE site_email_templates SET Content='$postdata[1]' WHERE ID = 1");
  } else if ($key == 2) {
    $update = $db->query("UPDATE site_email_templates SET Content='$postdata[2]' WHERE ID = 2");
  } else if ($key == 3) {
    $update = $db->query("UPDATE site_email_templates SET Content='$postdata[3]' WHERE ID = 3");
  }
}

如果不特别知道有多少个数组键,并将其全部保存在一个查询中,那么执行此操作的最简单方法是什么?

pdo

注意:我的答案是基于推荐答案驱动程序,它在很多方面都比mysqli更好。如果您需要mysqli解决方案,请查看the other answer provided by @Your Common Sense

以下代码在真实环境中进行了测试,并与阻止SQL注入的预准备语句一起使用:

$sql = "UPDATE `site_email_templates` SET `Content` = (:content) WHERE `Id` = (:id)";
$stmt = $dbConn->prepare($sql);
foreach ($postdata as $id => $content)
{
    $stmt->execute([':id' => $id, ':content' => $content]);
}

有关SQL注入的更多详细信息,请阅读:
https://www.owasp.org/index.php/SQL_Injection

相关文章