SQL – IF EXISTS UPDATE ELSE INSERT INTO

我想要做的是INSERT订阅服务器在我的数据库,但IF EXISTS它应该UPDATE行, ELSE INSERT INTO一个新的行。

当然,我先连接到数据库,并从urlstring中GET $name$email$birthday

 $con=mysqli_connect("localhost","---","---","---"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $name=$_GET['name']; $email=$_GET['email']; $birthday=$_GET['birthday']; 

这工作,但只是增加了新的一行;

 mysqli_query($con,"INSERT INTO subs (subs_name, subs_email, subs_birthday) VALUES ('$name', '$email', '$birthday')"); mysqli_close($con); 

这是我的尝试;

 mysqli_query($con,"INSERT INTO subs (subs_name, subs_email, subs_birthday) VALUES '$name', '$email', '$birthday' ON DUPLICATE KEY UPDATE subs_name = VALUES($name), subs_birthday = VALUES($birthday)"); mysqli_close($con); 

 mysqli_query($con,"IF EXISTS (SELECT * FROM subs WHERE subs_email='$email') UPDATE subs SET subs_name='$name', subs_birthday='$birthday' WHERE subs_email='$email' ELSE INSERT INTO subs (subs_name, subs_email, subs_birthday) VALUES ('$name', '$email', '$birthday')"); mysqli_close($con); 

 mysqli_query($con,"IF NOT EXISTS(SELECT * FROM subs WHERE subs_email='$email') Begin INSERT INTO subs (subs_name, subs_email, subs_birthday) VALUES ('$name', '$email', '$birthday') End"); mysqli_close($con); 

但是他们都没有工作,我做错了什么?

任何帮助是极大的赞赏!

  1. 在您的subs_email列上创build一个UNIQUE约束 (如果尚不存在):

     ALTER TABLE subs ADD UNIQUE (subs_email) 
  2. 使用INSERT ... ON DUPLICATE KEY UPDATE

     INSERT INTO subs (subs_name, subs_email, subs_birthday) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE subs_name = VALUES(subs_name), subs_birthday = VALUES(subs_birthday) 

您可以使用UPDATE子句中的VALUES(col_name)函数来引用来自INSERT的INSERT部分的列值… ON DUPLICATE KEY UPDATE – dev.mysql.com

  1. 请注意,我已经在string文字的地方使用了参数占位符,因为实际上应该使用参数化语句来抵御SQL注入攻击 。