Thursday, November 4, 2010

Prevent Multiple Submission of the Same Form

In this post I would like to suggest a way to guard against resubmitting the same form. If you don't have an option in your code, to prevent the same form from resubmitting then you can identify that your database is just filled with the same data.

We can point variety of reasons for resubmission the same form. Double clicking the submit button, hit their browser back button to edit or recheck the form and hit the submit button again are some examples.

You can place a unique Id in your form by using PHP uniqid() function, like shown below.

$unique_id = uniqid(microtime(), 1);
echo ''; //place this line your form to have a hidden field.



When saving the form data check whether the form is already saved in the database or not by checking the unique_id like below. If the unique_id is not exist then you save the form data in the database and the unique_id beside the form data.


$unique_id = $_POST['unique_id']; // I assumed that the form is submitted by post method.

$query = "SELECT * FROM your_table_name WHERE unique_id = '".$unique_id."'"; //in your table you need a column named unique_id.
$result = mysql_query($query);
if(mysql_num_rows($result)){
   //if true, the form is already submitted. Don't save.
}else{
   // save the form
}