$sql = "UPDATE Table SET ? = ? WHERE ID = ?";
$stmt = $pdo->prepare($sql);
foreach($QueryString as $Key=>$Value)
{
$stmt->execute($Key, $Value, $RecordID);
}
$sql = "UPDATE Table SET";
$v = 0;
foreach ($QueryString as $Key=>$Value) {
if ($v++ > 0) $sql .= ',';
$sql .= " `$Key` = ?";
}
$sql .= " WHERE ID = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute(array_merge(array_values($QueryString), array($RecordID)));
请注意,如果$QueryString
数组的键来自外部源,此查询仍然容易受到注入的攻击。为避免此问题,您应该使用手动指定的白名单来检查列是否确实存在,例如
$colnames = ['col1', 'col2', 'col3']; foreach ($QueryString as $Key=>$Value) { if (!in_array($Key, $colnames)) { // abort } if ($v++ > 0) $sql .= ','; $sql .= " `$Key` = ?"; }
或通过如information_schema.columns
中所述的从question表中获取列名的列表,并将该查询的结果用作白名单。