Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update database if Post value is not null

Tags:

sql

php

mysql

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.

like image 993
Bhavik P. Avatar asked Jan 23 '26 15:01

Bhavik P.


1 Answers

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.

like image 188
sgeddes Avatar answered Jan 26 '26 04:01

sgeddes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!