I have a form to update details of a user and they do not have to fill in every field. Because of that, it will be passing an empty string to the database via POST. This is my query:
$q = "UPDATE mdl_user SET firstname='$fname', lastname='$lname', email='$email',
address='$address', city='$city', school='$school', phone1='$phone'
WHERE id='$uid'";
Is there a way for MySQL to check if for example $fname
is an empty string and if it's empty don't update that field?
If not then how should I go about doing this in PHP?
In PHP, the empty string equals to a NULL value, but in MySQL, the case is the different i.e. empty string is not equal to NULL value. To understand the above syntax, let us create a column with NOT NULL constraint while you can insert an empty string.
NULL means the data is missing. An empty string "" is a blank string with the length of 0.
The IS NULL constraint can be used whenever the column is empty and the symbol ( ' ') is used when there is empty value.
You can use IF statement for each field you need to check. For example :
$q = "UPDATE mdl_user SET firstname=IF(LENGTH('$fname')=0, firstname, '$fname'), lastname=IF(LENGTH('$lname')=0, lastname, '$lname'), email=IF(LENGTH('$email')=0, email, '$email'), address='$address', city='$city', school='$school', phone1='$phone' WHERE id='$uid'";
I would do this
<?php
if ($fname) {
$fname = "firstname='$fname',";
} else {
$fname = '';
}
$q = "UPDATE mdl_user SET $fname lastname='$lname', email='$email', address='$address', city='$city', school='$school', phone1='$phone' WHERE id='$uid'";
?>
But you should really be worried about how insecure your code is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With