有人能用这种语法帮助我吗?我不知道我做错了什么!
当我尝试执行此代码时:
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
我不知道这段代码有什么问题!
答案 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'");
}