Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prevent MySQL from updating column with empty string?

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?

like image 924
user1219572 Avatar asked Mar 16 '12 13:03

user1219572


People also ask

Is empty string considered NULL in MySQL?

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.

What is empty string in MySQL?

NULL means the data is missing. An empty string "" is a blank string with the length of 0.

Is Empty in MySQL query?

The IS NULL constraint can be used whenever the column is empty and the symbol ( ' ') is used when there is empty value.


2 Answers

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'";
like image 57
Alex L Avatar answered Sep 30 '22 00:09

Alex L


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.

like image 26
Roderick Obrist Avatar answered Sep 30 '22 00:09

Roderick Obrist