简体   繁体   中英

Update database if Post value is not null

I am trying to update the table Users only if the $_POST[ value ] is not null. If it is null, the value already in the column should remain.

$query = "UPDATE `Users` 
SET FirstName = COALESCE(:firstName, FirstName), LastName = ISNULL(:lastName, LastName), City = :city, State = :state WHERE Email = :email";
$stmt = $dbh->prepare($query);
$stmt->bindValue(':firstName', $firstName);
$stmt->bindValue(':lastName', $lastName);
$stmt->bindValue(':city', $city);
$stmt->bindValue(':state', $state);
$stmt->bindValue(':email', $email);
$stmt->execute();

I tried COALESCE for the column FirstName and ISNULL for the LastName. COALESCE replaces my value with blank(NULL) which is exactly that opposite of what I want accomplished and ISNULL doesn't seem to work.

Assuming you mean COALESCE is replacing the FirstName with a blank (''), then try using NULLIF :

UPDATE `Users` 
SET FirstName = COALESCE(NULLIF(:firstName,''), FirstName) ...

I'm assuming the POST is posting a blank.

Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM