5

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?

3 Answers 3

11

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'";
Sign up to request clarification or add additional context in comments.

2 Comments

Hey, cheers. Can you explain what the second and third parameters in the IF clause means?
Hi. IF(<YOUR_CONDITION>, <VALUE_IF_TRUE>, <VALUE_IF_FALSE>). So if string length=0 then don't change it.
3

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.

7 Comments

Insecure? Are you sure? How do you know he's not escaping each of those variables?
One can assume these variables are properly sanitized after collection from the form. I hope ? The empty string will just add nothing to the QUERY, and since the column name is in it, it won't update it in the DB.
I hate to be rude, and no offence should be taken because we have all been there, but with a question this primative one could assume that he is not escaping.
@user1219572 It would not because you are taking out the whole assignment, it can either be a whole value, or nothing, note that the sql has had the firstname= part removed
Can you suggest any other ways because your code would imply that I would have to do an if statement for every single input? :/
|
-2

First run a SELECT statement and do a mysql_num_row() if this returns a value >0 then exit()

1 Comment

Select statement for what? :/ I just want to make sure I don't update a column with an empty string and thus overwriting any previous values in that column

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.