PHP: How to Fix Double Posting
When submitting a form, a user may click the submit button twice, they may reload the posted form, or hit back in their browser. Most of these will cause the form to be submitted twice and likely posted twice to the database.
Here’s one way to solve double posting, the process is:
- generate a unique key and include it with the form HTML
- when processing the form insert the unique key into the database table: transactions
- the transactions table has a UNIQUE INDEX on the key field
- if the insert fails, means there is a duplicate key, bail out of creating new one
- batch job runs daily to clean up old transactions so the insert and index is kept tidy
Here’s a bit of code, writing it on-the-fly, so you may have to fix any typos or forgotten semi-colons. We use smarty templates and have custom functions built, so not as easy to share the exact code.
First you need to setup your transactions table:
transaction_key varchar(24),
UNIQUE INDEX uki (transaction_key)
);
A simple PHP function to get a unique id, abstracted in case you want to change it later:
return uniqid(”, true);
}
The main function which checks if the key has been used before:
$return_value = db_insert(” INSERT INTO transactions (transaction_key) VALUES (‘$key’) “);
if ($return_value === false) { return false; }
else { return true; }
}
Your PHP+HTML Template Script:
<input type=”hidden” name=”transaction_key” value=”<?=get_transcaction_key()?>”>
… extra form stuff…
</form>
Your PHP Form Process Script:
… fun form processing …
}
NOTE: The sample code above should not be considered best practices. Your PHP+HTML should be in a nice template and you should scrub all your submitted variables before doing anything with them.
Comments are closed.







Or else, using javascript, you can hide the submit button when it’s been clicked once. It won’t help against spam (you probably already have a blocker anyway), but it’s easier to do.
thank you for yur help :)
So I was off work and surfing and found this place and thought I would join up. I don’t have much more to say right now except I need to start reading some of the older posts to get up to speed before I can start posting.
Em
Hi!
I want to improve my SQL knowledge.
I red that many SQL resources and want to
read more about SQL for my work as db2 database manager.
What can you recommend?
Thanks,
Werutz
thanks :) youre idea is good!
Hi Everbody
I just became a member of this forum
Great job by the admin, mods and seriously every member around.
A few days ago I read that there is a cure for diabetes on http://www.healthcaredaily.org
Is this way of curing diabetes mentioned actually true, If so I should have found out earlier! The source looks like a reliable healthcare news website
Could you someone tell me if this healthcare information is for real?
Thanks
SeixSpoiweell
B PLANI devrede Cumhurbaskan iyi Ve Irak’a su sozu