Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop data inserting into a database twice

Tags:

I was wondering what methods/preventions other programmers use to stop data being entered twice into a MySQL database when a user refreshes on the same page as a form? Obviouly it happens and I need a good way to stop this.

like image 884
Ben McRae Avatar asked Mar 12 '09 12:03

Ben McRae


People also ask

How can we prevent insertion of duplicate data?

Preventing Duplicates from Occurring in a Table. You can use a PRIMARY KEY or a UNIQUE Index on a table with the appropriate fields to stop duplicate records. Let us take an example – The following table contains no such index or primary key, so it would allow duplicate records for first_name and last_name.

How can we prevent duplicate entries in database in PHP?

1- Remove duplicate values using 'DISTINCT' key in mysql query, if it is present in table. 2- Check whether the value is present in table or not using PHP and Mysql before inserting data into the table. 3- We can also avoid duplicate values storing in mysql table while inserting by primary key.


1 Answers

I call this a golden rule of web programming:

Never ever respond with a body to a POST-request. Always do the work, and then respond with a Location: header to redirect to the updated page so that browser requests it with GET.

This way, refreshing will not do you any harm.

Also, regarding a discussion here in comments. To protect from double posting from, say, accidental doubleclicking the Submit button, store an md5() of your form in a text file, and compare the new form’s md5 to the stored one. If they are equal, you are having a double post.

like image 159
Ilya Birman Avatar answered Sep 28 '22 04:09

Ilya Birman