Looking to Build Web/Mobile Application ?

To speak to Rakshit, call +91 968 704 2303

Duplicate entry x for key PRIMARY Error Fixed in INSERT Query MySQL

Hi Friends,

Today i was working with mass upload features in shopping cart project. Here client can upload backup file with bulk data and we need to import all products in our database. Back up file consists of INSERT queries. Strangely, i found an error while working around which says “Duplicate entry x for key ‘PRIMARY'” and error code is 1062.

This error comes when you are trying to INSERT a records in MySQL database with the primary key which is already exists in that table. Once this query fails to insert records and throws error, it will terminate the execution of program. so better to use something which skip the duplicate record and continue with other records.

To achieve it, you can use INSERT … ON DUPLICATE KEY UPDATE instead of just INSERT MySQL statement. Here we go with the sample MySQL code for INSERT … ON DUPLICATE KEY UPDATE query.

Use INSERT … ON DUPLICATE KEY UPDATE Instead of INSERT

$sql = "INSERT INTO tbl_product 
  (id,v_name) 
VALUES 
  (1,'Nokia'),(1,'Samsung'),(2,'Sony'),(3,'Apple') 
ON DUPLICATE KEY UPDATE id = id";

When you use INSERT … ON DUPLICATE KEY UPDATE instead of INSERT statement, it will skip the duplicate record and keep executing remaining statements. Do you have questions like how to fix Duplicate entry x for key PRIMARY Error in INSERT Query MySQL or Duplicate entry x for key PRIMARY Error Fixed in INSERT Query MySQL than this is perfect solution for you.

If it helps you, please do not forget to share it to your social media circle. It might help your friends as well.

Share:

No Comments Yet.

Leave a Reply

Your email address will not be published.