如果不存在,则插入MYSQL数据库

时间:2017-10-17 05:26:03

标签: php mysql

我试图将客户添加到我创建的MySQL数据库中。 每当有人在网上商店订购商品时,客户就会被添加到数据库中(我不想要重复)。这是我的PHP代码:

$sqlInsert = "INSERT INTO Customers (FirstName, Address, Phone)
VALUES (".$userName.",".$address.",".$phone.")";

if(mysqli_query($conn, $sqlInsert)) {
    echo "new member registered successfully!";
} else {
    echo "Error: " . $sqlInsert . "<br>" . $mysqli_error($conn);
}

我已经研究过诸如INSERT INTO ... WHERE NOT EXISTS之类的查询。但我不理解我的案例的语法,也不知道它是否有效。 这是我的MYSQL客户表代码:

CREATE TABLE IF NOT EXISTS Customers (
PersonID INT(11) NOT NULL AUTO_INCREMENT, 
Email VARCHAR(100),
FirstName VARCHAR(100) NOT NULL,
LastName VARCHAR(100),
City VARCHAR(90),
Zip INT(10),
CustomerState VARCHAR(50),
Address VARCHAR(200),
Country VARCHAR(20),
Phone VARCHAR(50) NOT NULL,
PRIMARY KEY (PersonID)
);

2 个答案:

答案 0 :(得分:5)

INSERT INTO  Customers (FirstName, Address, Phone) 
SELECT * FROM (SELECT '$firstName', '$address', '$phone') AS tmp
WHERE NOT EXISTS (
    SELECT FirstName from Customers WHERE FirstName= '$firstName'
)   LIMIT 1;

这将阻止基于名字,您可以使用所有这些列进行检查,我假设匹配列应该是电子邮件,您可以使用它。

我刚刚在查询中添加了参数供您查询,使用参数绑定来避免sql注入。

OR

  select * from customers where .... // 

获取结果集的大小,如果size > 0表示已存在行,则不要插入。

MySQL: Insert record if not exists in table获取的sql语句并已修改。

答案 1 :(得分:0)

在插入之前尝试选择查询并检查行...尝试使用Mysqli Prepared语句。我按你的方式做这个代码......

    <?php 
    $sqlselect = "SELECT * FROM Customers WHERE FirstName = ".$userName." AND Address = ".$address." AND Phone = ".$phone;
    $exqry = mysqli_query($conn, $sqlselect);
    $cnt = count($exqry);
    if($cnt == 0){
      $sqlInsert = "INSERT INTO Customers (FirstName, Address, Phone)
      VALUES (".$userName.",".$address.",".$phone.")";

      if(mysqli_query($conn, $sqlInsert)) {
        echo "new member registered successfully!";
      } else {
        echo "Error: " . $sqlInsert . "<br>" . $mysqli_error($conn);
      }  
    }else{
echo "Member already in table.";
//do your update or other stuff.
}
    ?>