我正在尝试一个更新字段,管理员可以更新用户信息。我被密码卡住了。如果我现在更新并将密码留空,那么它会对空白值进行散列并将其插入DB。我想保留以前的值,除非在表格上更改。
我认为这最接近于我正在寻找的PHP MYSQL->如果变量不是';t为null或为空这并没有回答我的问题。除非我有多个查询,我猜是用if语句。真的,我只想让它更新编辑过的字段。
if(isset($_POST['register'])){
error_reporting(E_ERROR | E_PARSE | E_CORE_ERROR);
$username = !empty($_REQUEST['username']) ? trim($_REQUEST['username']) : null;
$pass = !empty($_REQUEST['password']) ? trim($_REQUEST['password']) : null;
$fname = !empty($_REQUEST['fName']) ? trim($_REQUEST['fName']) : null;
$lname = !empty($_REQUEST['lName']) ? trim($_REQUEST['lName']) : null;
$role = !empty($_REQUEST['role']) ? trim($_REQUEST['role']) : null;
$region = !empty($_REQUEST['region']) ? trim($_REQUEST['region']) : null;
$district = !empty($_REQUEST['district']) ? trim($_REQUEST['district']) : null;
$id = !empty($_REQUEST['ID']) ? trim($_REQUEST['ID']) : null;
$location = !empty($_REQUEST['store']) ? trim($_REQUEST['store']) : null;
$outlet = !empty($_REQUEST['outletid']) ? trim($_REQUEST['outletid']) : null;
$passwordHash = password_hash($pass, PASSWORD_BCRYPT, array("cost" => 12));
$sql=$pdo->prepare("UPDATE users
SET username = :username,
password = :password,
fName = :fName,
lName = :lName,
role = :role,
region = :region,
district = :district,
outlet_id = :outlet_id,
store_name = :store_name
WHERE id = :id
");
$sql->bindParam(':username',$username);
$sql->bindParam(':password',$passwordHash);
$sql->bindParam(':fName',$fname);
$sql->bindParam(':lName',$lname);
$sql->bindParam(':role',$role);
$sql->bindParam(':region',$region);
$sql->bindParam(':district',$district);
$sql->bindParam(':id',$id);
$sql->bindParam(':outlet_id',$outlet);
$sql->bindParam(':store_name',$location);
if($sql->execute()){
$_SESSION['success'] = "Successfully Updated Record";
}// End of if profile is ok
else{
print_r($sql->errorInfo()); // if any error is there it will be posted
$msg=" Database problem, please contact site admin ";
}
}
我尝试在语句中使用CASE,但这引发了一个错误。如何在不删除列中的数据的情况下更新用户数据?
IE:如果用户名被更改,那么只需在数据库中编辑该字段。如果用户名和密码被更改,请同时更新。
谢谢你们
编辑:
我试过这个
if(!empty(trim($_REQUEST['password']))){
$passwordHash = password_hash($pass, PASSWORD_BCRYPT, array("cost" => 12));
}
这仍然会更新密码
第2版:
"UPDATE users
SET username=:username,
password = CASE
WHEN :password = '' THEN password
ELSE :password
END,
fName=:fName,
lName=:lName,
role=:role,
region=:region,
district=:district,
outlet_id=:outlet_id,
store_name=:store_name
WHERE id=:id");
这是正确的方法。但若密码字段为空,您也应该使用else方法,以保持密码不变。
如果你想更新你的个人资料:
$userSql = $pdo->prepare("SELECT * FROM users where id = :id");
$userSql->bindParam(':id',$id);
$userSql->execute();
$user = $userSql->fetch();
if(trim($_REQUEST['password']) !== ''){
$passwordHash = password_hash($pass, PASSWORD_DEFAULT);
} else {
$passwordHash = $user['password']; //user password from db
}