一尘不染

SQL-如果存在,则将更新插入其他

mysql

我想要做的就是INSERT在我的数据库的用户,但IF EXISTS它应该UPDATE排,ELSE INSERT INTO一个新行。

Ofcourse我连接到数据库第一和GET$name$email$birthday从URL字符串。

$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);

但是它们都不起作用,我在做什么错?

任何帮助是极大的赞赏!


阅读 237

收藏
2020-05-17

共1个答案

一尘不染

  1. 如果不存在UNIQUE约束,请在您的subs_email列上创建约束

    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. 请注意,我已经使用参数占位符代替字符串文字,因为 实际上 应该使用参数化语句来防御SQL注入攻击
2020-05-17