如果已填充,则更新而不是INSERT

时间:2015-09-15 19:05:56

标签: php mysql mysqli

我正在编写一个CMS系统(我是PHP的新手),主要是为了学习这门语言,如果空的话我会遇到一个小的INSERT,如果一个记录已经存在,我就会陷入UPDATE。我有一个general_settings表,其中包含有关该网站的信息。我有一个名为常规设置的页面,您可以在其中插入网站标题,标语,徽标等数据到数据库。

但是,如果数据库中已有数据,而不是INSERT另一行,我想更新当前行...我该怎么做?我目前收到错误...

上传错误:

INSERT INTO general_settings (company_logo, site_title, site_slogan, site_address, email_address) VALUES ('Company Logo', 'Site Title', 'Slogan', 'SITE ADDRESS', 'EMAIL@EMAIL.COM') ON DUPLICATE KEY UPDATE general_settings set company_logo = 'Company Logo', site_title = 'Site Title', site_slogan = 'Slogan', site_address = 'SITE ADDRESS', email_address = 'EMAIL@EMAIL.COM' 

抛出:

  

您的SQL语法有错误;检查与您的MySQL服务器版本对应的手册,以便在'set company_logo ='Company Logo',site_title ='Site Title',site_slogan ='Slo'第1行附近使用正确的语法

页码:

<?php
    $servername = "localhost";
    $username = "REMOVED";
    $password = "REMOVED";
    $dbname = "REMOVED";

    $conn = new mysqli($servername, $username, $password, $dbname);

    if (mysqli_connect_errno()){
        echo 'Cannot connect to database: ' . mysqli_connect_error();
    } 

    else {
        $company_logo = mysqli_real_escape_string($conn, $_POST['company_logo']);
        $site_title = mysqli_real_escape_string($conn, $_POST['site_title']);
        $site_slogan = mysqli_real_escape_string($conn, $_POST['site_slogan']);
        $site_address = mysqli_real_escape_string($conn, $_POST['site_address']);
        $email_address = mysqli_real_escape_string($conn, $_POST['email_address']);
        $Query = "INSERT INTO general_settings (company_logo, site_title, site_slogan, site_address, email_address) VALUES ('$company_logo', '$site_title', '$site_slogan', '$site_address', '$email_address') ON DUPLICATE KEY UPDATE general_settings set company_logo = '$company_logo', site_title = '$site_title', site_slogan = '$site_slogan', site_address = '$site_address', email_address = '$email_address'";
        $conn->query($Query);
    }

    if ($conn->affected_rows <= 0){
        echo "Upload Error: <br><br> $Query <br><br>" . $conn->error;
        $conn->close();
    } 

    else {
        header ('location: /dashboard.php');
        $conn->close();
    }
?>

2 个答案:

答案 0 :(得分:2)

使用INSERT... ON DUPLICATE KEY UPDATE语法时,不应指定表名,也不应指定SET关键字。因此,您的查询应如下所示:

INSERT INTO general_settings
  (company_logo, site_title, site_slogan, site_address, email_address)
VALUES
  ('Company Logo', 'Site Title', 'Slogan', 'SITE ADDRESS', 'EMAIL@EMAIL.COM')
ON DUPLICATE KEY UPDATE
  company_logo = 'Company Logo', site_title = 'Site Title',
  site_slogan = 'Slogan', site_address = 'SITE ADDRESS', email_address = 'EMAIL@EMAIL.COM' 

答案 1 :(得分:0)

您需要实际拥有一个在查询中更新的密钥,一个主要密钥(假设它自动递增且不是手动插入的)并不算数

ALTER TABLE general_settings ADD CONSTRAINT myawesomekey UNIQUE (company_logo, site_title, site_slogan, site_address, email_address)

你知道,或类似的东西。