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?
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.
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).
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.
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
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.
You could change your query to INSERT IGNORE INTO table_name ...
this will prevent you from inserting twice.