0
$sql = "INSERT IGNORE INTO product (reference, description, price, created_at, updated_at)
VALUES ('{$sku}', '{$description}', '{$price}', '{$created_at}', '{$updated_at}')";

.. keeps on creating new rows because of the incrementing id column, how do I make SKU unique so it checks if SKU value exists, then UPDATE instead of INSERT.

6
  • Add a unique index on the reference column with ALTER TABLE or CREATE INDEX. Commented Jan 23, 2015 at 21:10
  • 1
    You may be able to use INSERT..ON DUPLICATE KEY. The SQL equivalent would be MERGE but that does not seem to be supported within MySQL. Commented Jan 23, 2015 at 21:10
  • 2
    @AnthonyForloney If he doesn't have a unique index, ON DUPLICATE KEY won't do anything. Commented Jan 23, 2015 at 21:11
  • Yes, I'm reading it but don't quite understand how to use. Just learning MySQL. :( Commented Jan 23, 2015 at 21:11
  • 1
    @Ismaestro All those answers assume you already have a unique key. They don't say how to create the unique key in the first place. Commented Jan 23, 2015 at 21:14

1 Answer 1

3

Add a unique key on the column you don't want to allow duplicates of:

ALTER TABLE product ADD UNIQUE KEY (reference);

Once you've done this, you can use the ON DUPLICATE KEY UPDATE clause to update the row instead of ignoring the INSERT.

INSERT INTO product (reference, description, price, created_at, updated_at)
VALUES ('{$sku}', '{$description}', '{$price}', '{$created_at}', '{$updated_at}')
ON DUPLICATE KEY UPDATE 
    description = VALUES(description),
    price = VALUES(price),
    created_at = VALUES(created_at),
    updated_at = VALUES(updated_at)

Using VALUES in the ON DUPLICATE KEY clause picks up the values that would have been assigned during an INSERT of a new row.

Sign up to request clarification or add additional context in comments.

5 Comments

This is done just once? or every time I make a query?
Just once. Indexes are part of the schema.
You need the unique key plus INSERT ... ON DUPLICATE KEY UPDATE.
Strange issue. Although the $conn->query($sql) === TRUE) passes and it reports row created successfully but I don't see many entries in the DB. One for example is 0213A5 which isn't in the DB. I'm also mysqli_real_escape_string the strings incase that's causing the error.
Figured it. There was a warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given so I changed it to $description_safe = mysqli_real_escape_string($conn, $description);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.