Forum Moderators: coopster
This all works fine but after entering a record, and returning to a database view page, a user can hit reload page and a new record is added.
Clearly, the previous $_POST vars are still in the system and thus reloading the page runs the same script to add a new record.
New records should only be added when the submit button is pressed but after doing that successful, subsequent page refreshes repeats the procedure.
How do I prevent this?
There could be valid duplicates in some fields. I guess I need to check that a record does not contain the same info for all fields:
if ($_POST['field1'] == $row['field1'] && $_POST['field2'] == $row['field2'] && $_POST['field3'] == $row['field3'] && $_POST['field4'] == $row['field4'] )
{
//do nothing
} else {
// add new record
}
Just wondering if there is an easier way.
Is it possible to null the $_POST vars after a successful database insert? Something like:
(rough coding)
if($_POST['update_submitted']) {
$query="INSERT into db1 (field1...) values ($_POST['field'])";
$_POST['update_submitted'] = '';
It shouldn't produce a duplicate as the part which inserts the record won't be run:
if($_POST['update_submitted') {
// sql insert here
}
Unfortunately that method doesn't work. You can't force an overwrite of a $_POST. It will restore itself on reload.
Having had time to think of this I came up with two solutions.
The first is to set a flag on successful insert which turns off the hidden flag in the form:
if($_POST['update_submitted') {
// sql insert here
$already_did_this = 1;
} else {
$already_did_this = 0;
}
.
.
.
<FORM....
if($already_did_this == 0) {
print <input type="hidden" name="update_submitted">
That would work but there is an even easier way. All you have to do is to send a header to reload the page afer the data is inserted:
if($_POST['update_submitted') {
// sql insert here
header("location: [widgets.com...]
}
The header("location... bit forces a clean reload where all post and get vars are gone.