Category Archives: PHP

Preventing Duplicate Record Insertion on Page Refresh

Most of beginners (including me) face these problems inserting data into database.

When clicking submit button after filluping a form if you refresh the form it will insert the duplicate data. There are two solutions that I know from Google search. May be you can find more by Google search.

And since you cannot avoid a refresh of the screen…

<form action=”insert.php” method=”POST”>
<input type=”text” name=”name”>
<input type=”text” name=”telephone”>
<input type=”text” name=”email”>
<input type=”sumbit” name=”submit”>
</form>

1) If you are doing a form post, you might consider sending a location
header AFTER you inserted the record:

insert.php
// after inserting the data
header(“Location: thanks.php“);
exit();
// do not forget the exit, since your script will run on without it.

In that way your script will process the posting, and then redirects the
browser to thanks.php. This page will contain a message (Thank You). A reload of thanks.php will not result in a fresh db insert.

2) If you’re using sessions, generate serial and supply it as hidden field with
every posting form. Increase it at every post and decline to store data if
serial in the _POST isn’t equal to the one stored in _SESSION.

Combining it with redirects (always good to have such protection), you’ll
probably never got the duplicated submits.