如何使用两个数组构造 UPDATE 语句

问题描述 投票:0回答:1

所以我有一个列标题数组和一个位于同一索引的相应值数组 我需要在 SQL 中使用这两个数组来更新一行。

我知道这可能不是最好的方法。我如何获得这些值是我获取 SQL 数据库列并使用它们生成一个 HTML 表单,该表单给出了这些值,因此为什么两者都在一个数组中

使用 INPUT 我的 SQL 看起来像这样并且按照我想要的方式工作:

$strcol = implode(",", $fieldname);
$strdata = implode(",", $fielddata);
$placeholders = str_repeat(" ?, ", count($fielddata)-1) . "?";

print_r($placeholders);
$sql = "INSERT INTO morning (" . $strcol . ")
VALUES (". $placeholders . ")";
print_r($sql);
$result = $conn->execute_query($sql, $fielddata);

得到的结果类似于:

但是我不知道如何对更新执行相同的操作,我可能在某个地方错过了一个非常明显的解决方案

php sql mysql mysqli
1个回答
2
投票
// find the value of the primary key (assuming it is "id")
$idKey = array_search("id", $fieldname);
if ($idKey === false) {
  // return error because the data does not include the primary key
}
$idValue = $fielddata[$idKey];

$assignments = implode(", ", array_map(function($col) { return "`$col`=?"; }, $fieldname));
    
$sql = "UPDATE morning SET {$assignments} WHERE id=?";
$result = $conn->execute_query($sql, array_merge($fielddata, [$idValue]));
© www.soinside.com 2019 - 2024. All rights reserved.