您可以动态构建查询。
$fields = array();
foreach($_POST as $key => $value) {
// Only grab whitelisted fields
if (in_array($key, array('field_1', 'field_2', 'field_3'))) {
if (!empty(trim($value))) {
// Using the keys from $_POST assumes they are named after their database counterparts
$fields[$key] = trim($value);
}
}
}
// Grab the keys (fieldnames) so we can use them to build the query
$keys = array_keys($fields);
$sqlFieldsPart = implode(', ', array_map(function($field) {
return $field . '= :' . $field;
}, $keys));
$sql = sprintf('UPDATE tablename SET %s WHERE somefield=:somefield', $sqlFieldsPart);
$dbh = new PDO('mysql:hostname=localhost;dbname=yourdb', 'username', 'password');
$stmt = $dbh->prepare($sql);
// Modify keys on $fields
$data = array();
foreach ($fields as $key => $value) {
// Note the colon before the key variable, this is necessary
// It links to the placeholders in the query
$data[':' . $key] = $value;
}
// Set the value for the where clause
$data[':somefield'] = 'somevalue';
// Execute the statement, passing the data to the execute function
$stmt->execute($data);
此代码假定您的 html 字段以其数据库对应项命名。如果不是这种情况,您可以从第一个 foreach 循环中为每个字段硬编码或进行某种字段映射。