在重复密钥更新语法上仍然复制我的数据

时间:2017-08-31 19:13:53

标签: mysql

我理解这个问题可能会被问到,但我尝试使用我在这里找到的解决方案,但他们并没有为我工作。如果电子邮件列存在,我需要更新数据库中的数据,否则应该插入新记录。 以下是我的代码。

       <?php

    $dbhost = 'localhost';
    $dbuser = 'root';
    $dbpass = '';
    $db = 'mbf';

    $dbconn = mysql_connect($dbhost, $dbuser, $dbpass);
    mysql_select_db($db);



    $dat = date("Y-m-d H:i:s");
    $date = new DateTime();
    $date->modify('+4 weeks');


    if(isset($_POST['submit'])) {

    $email = $_POST['email'];

          $dat = $_POST['date'];
          $ghdate = $_POST['ghdate'];
             $amount =    $_POST['amount'];
            $iniamount = $_POST['iniamount'];
           $outamount = $_POST['outamount'];
         $ghamount = $_POST['ghamount'];




         $query = "INSERT INTO donation (email, date, ghdate, amount, 
   inamount, outamount, ghamount) VALUES ('$email', '$dat', 
   '$ghdate','$amount', 
 '$iniamount', '$outamount', '$ghamount')
         ON DUPLICATE KEY UPDATE
email='$email', date='$dat', amount='$amount', inamount='$iniamount', 
outamount='$outamount', ghamount='$ghamount'";


if(mysql_query($query))
 {
 echo "<script>alert('Donation of $amount was successful');</script>";
}
 else
 {
 echo "<script>alert('FAILED TO INSERT');</script>";
 }

 }


?>

它不会更新电子邮件列,而是会插入新记录。

1 个答案:

答案 0 :(得分:2)

仅当任何字段值违反UNIQUE / PRIMARY KEY约束时,

ON DUPLICATE KEY UPDATE语句才有效。确保电子邮件字段在表模式中具有UNIQUE约束。