Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle error for duplicate entries?

I have a PHP form that enters data into my MySQL database. My primary key is one of the user-entered values. When the user enters a value that already exists in the table, the MySQL error "Duplicate entry 'entered value' for key 1" is returned. Instead of that error, I would like to alert the user that they need to enter a different value. Just an echoed message or something.

How to turn a specific MySQL error into a PHP message?

like image 544
RobHardgood Avatar asked Jun 30 '10 06:06

RobHardgood


People also ask

How do I ignore duplicate entries?

Use the INSERT IGNORE command rather than the INSERT command. If a record doesn't duplicate an existing record, then MySQL inserts it as usual. If the record is a duplicate, then the IGNORE keyword tells MySQL to discard it silently without generating an error.

What causes duplicate entries?

Data aggregation and human typing errors are some of the sources of duplicate data. Customers may also provide a company with different information at different points in time. Hence, businesses should consider removing duplicate records from their Database.


Video Answer


2 Answers

To check for this specific error, you need to find the error code. It is 1062 for duplicate key. Then use the result from errno() to compare with:

mysqli_query('INSERT INTO ...'); if (mysqli_errno() == 1062) {     print 'no way!'; } 

A note on programming style
You should always seek to avoid the use of magic numbers (I know, I was the one to introduce it in this answer). Instead, you could assign the known error code (1062) to a constant (e.g. MYSQLI_CODE_DUPLICATE_KEY). This will make your code easier to maintain as the condition in the if statement is still readable in a few months when the meaning of 1062 has faded from memory :)

like image 74
jensgram Avatar answered Oct 09 '22 21:10

jensgram


You can check the return value from mysql_query when you do the insert.

$result = mysql_query("INSERT INTO mytable VALUES ('dupe')");  if (!$result) {     echo "Enter a different value"; } else {     echo "Save successful."; } 
like image 38
nickf Avatar answered Oct 09 '22 19:10

nickf