if else mysql语法

时间:2014-06-20 18:36:01

标签: mysql

有人能用这种语法帮助我吗?我不知道我做错了什么!

当我尝试执行此代码时:

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';

我收到以下错误:

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

我不知道这段代码有什么问题!

3 个答案:

答案 0 :(得分:1)

您是否尝试在END IF声明之后添加INSERT INTO...

答案 1 :(得分:0)

您需要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'

您必须将列user_name设为UNIQUE

如果它不唯一,那么

ALTER IGNORE TABLE user ADD UNIQUE (user_name);

答案 2 :(得分:0)

下面这段代码为我做了诀窍:

$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'");
}