我有一個更新表單來更新用戶資訊。在這里,我輸入了密碼。我想,如果留空,不更新資料庫中的密碼,而是保留已經設定的密碼。
為此,我有:
$user_password = inputCleaner($_POST['user_password']);
$user_password_repeat = inputCleaner($_POST['user_password_repeat']);
// IF filled, check if both match
if (!empty($user_password) && $user_password != $user_password_repeat) {
$errors .= "Passwords are not the same." . '<br>';
} elseif (!empty($user_password) && $user_password == $user_password_repeat) {
$user_password = hash('sha512', $user_password);
}
// IF NOT FILLED, leave NULL
elseif (empty($user_password)) {
$user_password = '';
}
如果一切順利,我們運行腳本:
if(!$errors) {
$statement = $connection -> prepare("
UPDATE users SET
user_nickname = :user_nickname,
user_password = COALESCE(NULLIF(:user_password, ''),user_password)
user_pass
user_name = :user_name,
user_last_name = :user_last_name,
user_email = :user_email,
user_picture = :user_picture,
role = :role
WHERE
user_id = :user_id
");
$statement -> execute(array(
':user_nickname' => $user_nickname,
':user_password' => $user_password,
':user_name' => $user_name,
':user_last_name' => $user_last_name,
':user_email' => $user_email,
':user_picture' => $user_picture,
':role' => $role,
':user_id' => $user_id
));
注意我的 inputCleaner() 函式很簡單:
function inputCleaner($input) {
$input = trim($input);
$input = stripslashes($input);
$input = htmlspecialchars($input);
return $input;
}
有了這個,密碼根本不會更新,它不會改變它。
uj5u.com熱心網友回復:
相反轉換的''到NULL,然后使用COALESCE(),你可以簡單地比較:user_password來''。
您還遇到了一些語法錯誤:分配給之后缺少逗號,之后又多user_password了一行user_pass。
$statement = $connection -> prepare("
UPDATE users SET
user_nickname = :user_nickname,
user_password = IF(:user_password = '',user_password, :user_password),
user_name = :user_name,
user_last_name = :user_last_name,
user_email = :user_email,
user_picture = :user_picture,
role = :role
WHERE
user_id = :user_id
");```
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/389884.html
