89

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

当然,我首先连接到数据库,然后GET从url 字符串连接到数据库。$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);

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

任何帮助是极大的赞赏!

4

2 回答 2

220
  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 ... ON DUPLICATE KEY UPDATE 的 INSERT 部分的列值 - dev.mysql.com

  1. 请注意,我使用参数占位符代替了字符串文字,因为确实应该使用参数化语句来防御 SQL 注入攻击
于 2013-03-13T11:26:37.450 回答
2

试试这个:

INSERT INTO `center_course_fee` (`fk_course_id`,`fk_center_code`,`course_fee`) VALUES ('69', '4920153', '6000') ON DUPLICATE KEY UPDATE `course_fee` = '6000';
于 2020-10-16T04:34:04.457 回答