这是一个函数,它将采用输入数组并生成可以直接放入查询的内容,只要您只更新单个表:
function array_to_pdo_params($array) {
$temp = array();
foreach (array_keys($array) as $name) {
$temp[] = "`$name` = ?";
}
return implode(', ', $temp);
}
现在您可以像这样执行PDO查询:
// The data
$data = array(
'name' => 'Objective',
'short_name' => 'OB',
'generation' => 1
);
// The parameter for the WHERE clause
$sid = 1;
// Build the query string
$query = "
UPDATE `signals`
SET ".array_to_pdo_params($data)."
WHERE `sid` = ?
";
// Convert the data array to indexed and append the WHERE parameter(s) to it
$queryData = array_values($data);
$queryData[] = $sid;
$stmt = $db->prepare($query); // Obviously add the appropriate error handling
$stmt->execute($queryData);