0

Can anybody help me in this syntax? I don't know what wrong am I doing!

When I try to execute this code:

IF EXISTS(SELECT * FROM user WHERE user_username = '$user_username') 
THEN
UPDATE user SET user_name='$name',user_profession='$profession',user_address='$address',user_avatar='$NewImageName'
ELSE 
INSERT INTO user (user_name,user_profession,user_address,user_avatar) VALUES ('$name','$profession','$address','$NewImageName';

I get the following error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF EXISTS(SELECT * FROM user WHERE user_username = '111') THEN UPDATE user SE' at line 1

I don't know what is wrong with this code!

4
  • @tsHunter yes he does. dev.mysql.com/doc/refman/5.0/en/if.html Commented Jun 20, 2014 at 18:38
  • 1
    use insert .. on duplicate key update syntax Commented Jun 20, 2014 at 18:39
  • I was trying to UPDATE the table when the IF EXISTS part is TRUE. Else, I wanted to INSERT into the table. Commented Jun 21, 2014 at 1:35
  • I don't need an ON DUPLICATE key. Commented Jun 21, 2014 at 1:36

3 Answers 3

1

Have you tried adding an END IF after the INSERT INTO... statement?

Sign up to request clarification or add additional context in comments.

3 Comments

There also needs to be a ) before the ; at the end of your VALUES statement.
@NirmalyaGhosh Great! If this answered the question for you would you mind accepting it as the answer? Thanks.
@NirmalyaGhosh I see it now. Sorry about that.
0

you need ON DUPLICATE KEY

INSERT INTO user (user_name,user_profession,user_address,user_avatar)
VALUES ('$name','$profession','$address','$NewImageName'
   ON DUPLICATE KEY
UPDATE user SET user_name='$name',
                user_profession='$profession',
                user_address='$address',
                user_avatar='$NewImageName'

you must have column user_name as UNIQUE

if its not unique do this

ALTER IGNORE TABLE user ADD UNIQUE (user_name);

1 Comment

he doesn't need an ON DUPLICATE KEY, he needs a working IF statement. Your proposing another solution, but this is not an answer, is it?
0

The following piece of code did the trick for me:

$result = mysql_query("SELECT * FROM user WHERE user_username = '$user_username'");
if( mysql_num_rows($result) > 0) {
    mysql_query("UPDATE user SET user_name='$name',user_profession='$profession',user_address='$address',user_avatar='$NewImageName' WHERE user_username = '$user_username'");
}
else
{
    mysql_query("INSERT INTO user (user_name,user_profession,user_address,user_avatar) VALUES ('$name','$profession','$address','$NewImageName') WHERE user_username = '$user_username'");
}

Comments

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.