1

I'm trying to add a customer to the MySQL database I created. Whenever somebody orders an item on the online store, the customer is added to the database (I dont want duplicates). Here is my php code:

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

I have looked into queries such as INSERT INTO... WHERE NOT EXISTS. But I don't understand the syntax for my case, and don't know if it would work. here is my MYSQL customer table code:

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)
);
Dinal Koyani
  • 461
  • 3
  • 6

2 Answers2

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;

This will prevent based on the first name, you may use all these columns for checking, I assume the matching column should be email, you can use that.

I just added the parameters within the query for you to get an idea, use parameter binding to avoid sql injection.

OR

  select * from customers where .... // 

Get the size of result set and if size > 0 that means there is a row already, so do not insert it.

Sql statement taken from MySQL: Insert record if not exists in table and modified.

Danyal Sandeelo
  • 11,068
  • 6
  • 37
  • 64
  • Nice Explanation @Danyal – Nawin Oct 17 '17 at 05:36
  • @DanyalSandeelo - could you, or someone, provide this example with parameter binding please. I see 4 variables in the above example...would that be 4 bindings, wiht the `$firstname` repeated twice? iE: array($firstName,$address,$phone,$firstName) – rolinger Sep 12 '18 at 05:01
0

Try select query before insert and check the rows...Try to use Mysqli Prepared statement. I do this code for your way...

    <?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.
}
    ?>
Nawin
  • 1,505
  • 1
  • 12
  • 22