function pdoSet($fields, &$values, $source = array()) {
$set = '';
$values = array();
if (!$source) $source = &$_POST;
foreach ($fields as $field) {
if (isset($source[$field])) {
$set.="`".str_replace("`","``",$field)."`". "=:$field, ";
$values[$field] = $source[$field];
}
}
return substr($set, 0, -2);
}
This function will produce a correct sequence for the SET operator,
`field1`=:field1,`field2`=:field2
to be inserted into query and store avtual data values in $values
array for execute()
.
$fields = array('id','name','age','loc'); // allowed fields
$sql = "INSERT INTO `user` SET".pdoSet($fields,$values);
$stm = $dbh->prepare($sql);
$stm->execute($values);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…