I've a php web page with a form. After filling the form in web page, I can submit it to the server. But after that, if I refresh the page, it inserts the same record to the database. Is there any solutions to this problem?

+1  A: 

Yep, do two queries. The first checks to make sure the data doesn't already exist in the DB, the second one does the insert if there is no duplicate data. There are a bunch of ways to go about checking to make sure the duplicate data doesn't exist, but this is the basic process you will want to go through.

Mike Keller
+2  A: 

There are a number of ways, for example:

  • Create a token which you insert into the form (hidden field). if the same token is submitted twice, discard the second submit.
  • Check in the database if an identical post already exists.
  • Save the form submit in a session variable.
  • Redirect the user to a second page after the submit, using the Post/Redirect/Get pattern (preferably in combination with one of the above).
Emil Vikström
+1: form authentication tokens. Also help guard against CSRF.
Andrew Aylett

Before inserting to the database check whether the same values are duplicates already, and if they are duplicates, don't insert. Checking for multiple columns helps even further. For example, instead of checking just for a "username", you would check for a "username" AND "password".

Obviously the examples above are fake, but you should get the point.

Raphael Caixeta
+5  A: 

Use the POST/Redirect/GET pattern. This will prevent the user from being able to resubmit the same form.


You can make a process.php page and set your form's action to it.

In process.php

//code to insert item to database
header('Location: YOUR_FORM_PAGE_HERE);

Then it will send them back to the original page and there won't be any post data

Browsers are not required to send the HTTP_REFERER header, it can be blank.
@Douglas, thanks I changed it. If he knows the location he won't need it. I just used HTTP_REFERER for the sake of generalizing
+1  A: 

Well, that's what Refresh means: "do it again."

You can check to see if data that matches the submitted data is already in the database. If so, you can reject the new submission.

Scott Saunders

You could change your query to INSERT IGNORE INTO table_name ...

this will prevent you from inserting twice.