0

This is my first UPDATE query, I have checked using jQuery for any empty fields. I want the user to input at least one field and then update the field(s). Doing a query with all the $_POST names might generate empty or undefined input fields in my database which doesn't work.. here is my query:

$first = $_POST['first'];
$last = $_POST['last'];
$birth = $_POST['birth'];
$bio = $_POST['bio'];

$UID = $_SESSION['id'];

$query = "UPDATE `user` SET `firstname`=$first,`lastname`=$last,`birthday`=$birth,`biography`=$bio WHERE `user_id` = '$UID'";
$result = mysql_query($query) or die($result . "<br/><br/>" . mysql_error());

The error: syntax to use near 'birthday=,biography= WHERE user_id = '11'' at line 1

I don't want to go through nested if's to check whether has a value or not. Thanks.

1
  • Please use prepared statements to avoid SQL injections. Commented Dec 26, 2013 at 9:26

1 Answer 1

1

NOTE: Use mysql_real_escape_string() to prevent from sql injection.

if( !empty($first) && 
    !empty($last) && 
    !empty($birth) && 
    !empty($bio) ){

$query = "UPDATE `user` 
             SET 
               `firstname`='$first',
               `lastname`='$last',
               `birthday`='$birth', 
               `biography`='$bio' 
           WHERE `user_id` = '$UID'";
}
Sign up to request clarification or add additional context in comments.

3 Comments

ok this is working, but they are updating the empty fields, so I have to check for this one?
@Atieh yes you have to check empty fields before update, otherwise it update empty value on every refresh, check the updated answer.
I got the idea, but this isn't my case, if it's empty I will set it to the current value..thanks!

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.