2 回答
TA贡献2080条经验 获得超4个赞
尽管未经测试,但您可以做的是使用表单字段名称和数据库列名称的数组来帮助以更安全的方式动态构建您的 sql,使用prepared statement
if( !empty( $_SESSION['user_info'] ) && $_SERVER['REQUEST_METHOD']=='POST' ) {
$fields=array(
'account_details_first_name' => 'first_name',
'account_details_last_name' => 'last_name',
'account_details_phone_number' => 'phone_number',
'account_details_address_1' => 'address_1',
'account_details_address_2' => 'address_2',
'account_details_city' => 'city',
'account_details_post_code' => 'post_code',
'account_details_country' => 'country'
);
/* default variables... */
$user_id = array_values( $_SESSION['user_info'] )[9];
$edited = date('d.m.Y h:i a');
/* placeholders used to generate sql statement */
$params=array();
$values=array();
$types=array();
/*
iterate through all submitted POST fields -
if they are not empty add them to the placeholders
*/
foreach( $_POST as $field => $value ){
if( !empty( $value ) ){
$params[]=sprintf( '`%s`=?', $fields[ $field ] );
$values[]=$value;
$types[]='s';
}
}
/*
add semi-static variables to placeholders too
*/
$values[]=$user_id;
$types[]='s';
/* create a sql statement and the use that to create the `prepared statement` */
$sql = sprintf( 'update `users` set %s where `id`=?', implode( ',', $params ) );
#echo $sql;
$stmt=$db->prepare( $sql );
/* bind the types and assign variables with a SPLAT */
$stmt->bind_param( implode('',$types), ...$values );
$result=$stmt->execute();
echo $result ? 'Record updated successfully' : 'Error updating record';
}
通过echo在任何调用之前退出 SQL,$db我能够生成以下 SQL,它看起来可以在以下环境中使用prepared statement:
update `users` set `first_name`=?,`last_name`=?,`phone_number`=?,`address_1`=?,`address_2`=?,`city`=?,`post_code`=?,`country`=? where `id`=?
没有架构和数据,我无法进一步测试,但看起来还不错。现在是时候喝杯酒了……
TA贡献1777条经验 获得超10个赞
您需要使用 ',' 而不是 'and' 来分隔字段,我建议您使用受函数 htmlspecialchars 保护的 xss,请参阅如何使用 HTML/PHP 防止 XSS?. 尝试这个:
if(isset($_POST['account_details_submit'])) {
$valuesToUpdate = [];
$fields = [
'first_name' => 'account_details_first_name',
'last_name' => 'account_details_last_name',
'phone_number' => 'account_details_phone_number',
'address_1' => 'account_details_address_1',
'address_2' => 'account_details_address_2',
'city' => 'account_details_city',
'post_code' => 'account_details_post_code',
'country' => 'account_details_country'
];
foreach ($fields as $key => $field) {
$protectedFromXss = trim(htmlspecialchars($_POST[$field]));
if ($protectedFromXss) {
$valuesToUpdate[] = "$key = '$protectedFromXss'";
}
}
if (count($valuesToUpdate)) {
$values = ', ' . implode(', ', $valuesToUpdate);
}
$edited = date('d.m.Y h:i a');
$user_id = array_values($_SESSION['user_info'])[9];
$update = "UPDATE `users` SET `edited` = '{$edited}' {$values} WHERE `id` = '$user_id'";
if ($conn->query($update) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
- 2 回答
- 0 关注
- 83 浏览
添加回答
举报