Prevent duplicate record insert on manual page refresh

I have a problem which has only just surfaced itself.

I'm working in a MVC environment. The method names in my interface class match those of the request module and action i.e. ?module=test&action=action would result in a method called public function test_action() { }

In this particular problem, I have a form which submits to itself. If validation passes, a record is created and I then show the template of another module. This module expects a series of post variables as it is used in two modules.

The problem I'm having is that, if the user successfully passes the validation and attempts to F5 the page, another new record is created etc.

How can I prevent this from happening?

Normally I would header redirect after a successful insert but in this instance I can't.

--------------Solutions-------------

I would take it a complete other way. I even find redirection an incorrect way of handling this, since changing locations is not meant to overcome logic/form troubles.

The correct solution is:

  • Add a unique hash to your form in a hidden input
  • Store the hash in a server-side session
  • When the form is send, validate the hidden input hash with the hash on your server
  • Only execute row insertion when the form validates correctly.

If you are working with Zend Framework, there is a Zend_Form_Element_Hash class for you.

Developer error:

You need to create a handler page which:

  • validating sent data
  • insert row
  • redirect user

You can / should re-direct to a new page after successful insertion.

As you are working in MVC, you can add a new controller that just calls the view you want to show.

Here is what I do it. This is working for me. Hope it can help anyone else.

//+++ start token +++
//This is to prevent duplicate entry on page reload (F5). 19. If I enter all values, press Record in journal and then press F5, the same values are recorded one more time. Need to prevent

// 3rd. $token_hash_from_input get value of input field name name="' .$_SESSION['token_hash'] .'"
$token_hash_from_input = $_SESSION['token_hash'];
//echo $token_hash_from_input .' token_hash_from_input<br>';
//echo $_POST[$token_hash_from_input] .' $_POST[$token_hash_from_input]<br>';
//var_dump($token_hash, $_POST);

// 4th. $_SESSION['token'] created/set in 1st. Then it as if goes around (at first to input field then after page reload returns here). However $_POST[$token_hash_from_input] is value received directly from input field. User click post and input field value is passed to $_POST[$token_hash_from_input]. Here I compare both.
if ( $_SESSION['token'] != htmlspecialchars($_POST[$token_hash_from_input]) ) {
$token_error .= 'yes';
//echo 'session token and token from input field are not the same <br> ';
}
else {
//echo 'session token is equal to post$token_hash)<br>';
}

// 1st. Create token and pass it to session
$token = sha1(uniqid(mt_rand(), true));
$_SESSION['token'] = $token;
//echo $_SESSION['token'] .' new $_SESSION[token]<br>';//after each page reload new token created. Then this token passed to input form (hidden field). value="' .$_SESSION['token'] .'"

// 2nd. Create token_hash and pass it to session. Token hash is to name input fields name and id. I may not use $token_hash and $_SESSION['token_hash']. Instead of this I can use name="token" and id="token".
$token_hash = sha1(uniqid($time_when_form_submitted .'token' .$_SERVER["REMOTE_ADDR"]));
//echo $token_hash .' $token_hash<br>';
$_SESSION['token_hash'] = $token_hash;
//echo $_SESSION['token_hash'] .' new SESSION$token_hash<br>';
// +++ end token +++

Input field like this

<input type="hidden" name="' .$_SESSION['token_hash'] .'" id="' .$_SESSION['token_hash'] .'" value="' .$_SESSION['token'] .'">

or

<input type="hidden" name="<?php echo $_SESSION['token_hash'] ?>" id="<?php echo $_SESSION['token_hash'] ?>" value="<?php echo $_SESSION['token'] ?>">

I suppose code can be improved (I have no good knowledge php etc)

"Normally I would header redirect after a successful insert but in this instance I can't."

are you facing some error in doing that?

If for whatever reason you can't redirect (Which sounds peculiar) you can use the 'same' mechanism used for data validation to flush the forms after a successful insert.

But that's a really ugly way to go.

One of most common issue which many of the web developers face in their web applications, is that the duplicate records are inserted to the Database on page refresh. If the web page contains some text box and a button to submit the textbox data to the database. In that case when the user insert some data to the textbox and click on the submit button, it will save the record to the Database and then if the user refresh the web page immediately then the same record is again saved to the database as there is no unique keys that can be used to verify the existence of the data, so as to prevent the multiple insertion.

From this behavior we can definitely know that, on the page fresh the button click event is fired. To avoid this problem we can try this method as discuss below.

On page load event save the date/time stamp in a session variable, when the page is first loaded, a Session variable is populated with the current date/time as follows:

*void Page_Load(Object sender, EventArgs e) { if(!IsPostBack) { Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString()); } }*

On the page's PreRender event, a ViewState variable is set to the value of the Session variable as follows:

void Page_PreRender(object obj,EventArgs e)
{
ViewState["update"] = Session["update"];
}

Then these two values are compared to each other immediately before the database INSERT command is run. If they are equal, then the command is permitted to execute and the Session variable is updated with the current date/time, otherwise the command is bypassed as given below:

void btnSubmit_Click(object obj, EventArgs e)
{
string name = "";
string qualification = "";

if (Session["update"].ToString() == ViewState["update"].ToString())
{
if (txtName.Text != "" || txtName.Text != null)
{
name = txtName.Text.ToString();
}

if (txtQualification.Text != "" || txtQualification.Text != null)
{
qualification = txtQualification.Text.ToString();
}

//--- Insert data function should be execute here

string strSql = "INSERT INTO Testdata (Name,Qualification) VALUES ('" + name + "','" + qualification + "')";

SqlConnection ANConnection = new SqlConnection(ConnectionString);

ANConnection.Open();
SqlCommand ANCommand = new SqlCommand(strSql, ANConnection);
ANCommand.ExecuteNonQuery();

ANConnection.Close();
ANConnection.Dispose();

//--End of save data

lblMessage.Text = "Inserted Record Sucessfully
Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
}
else
{
lblMessage.Text = "Failure – Due to Page Refresh";
txtName.Text = "";
txtQualification.Text = "";
}
}

Category:php Time:2010-09-16 Views:1
Tags: php refresh

Related post

  • Prevent duplicate record insertion on refresh without redirecting 2011-01-30

    I have this bit of script: if (isset($_POST['comment_posted'])) { $user_comment = mysql_real_escape_string($_POST['user_comment']); $add_user_comment = Event::addUserComment($id,$user->user_id,$user_comment); } After a user submits his comment, an

  • How do you fix word so that when you insert a manual page break, the document continues on the same screen/page? 2012-02-21

    I have documents that only have a few lines on each page. It is a pain in the neck to have to keep scrolling down to get to the next page. --------------Solutions------------- I have documents that only have a few lines on each page. It is a pain in

  • How to prevent duplicate records being inserted with SqlBulkCopy when there is no primary key 2010-04-07

    I receive a daily XML file that contains thousands of records, each being a business transaction that I need to store in an internal database for use in reporting and billing. I was under the impression that each day's file contained only unique reco

  • New row inserted for each page refresh 2009-12-31

    Hi I'm getting a strange problem while inserting records into database. In my button click event I'm trying to insert some values into my database it is working fine. Once insertion is completed... again if I press F5 or refresh the browser a new row

  • Preventing duplicate records across multiple connections using Rails 2011-01-13

    I have two separate processes, each with it's own database connection, inserting product records into a table. Before a process inserts a product into the table, it checks to see if a product with the same properties already exists. If the product al

  • MVC Entity Framework validation to prevent duplicate records 2011-09-16

    Hi i'm new to MVC and EF so this may be a really simple question but what is the best way to prevent the user from trying to enter duplicate records? I have a simple look up table with one column which is the primary key. I'm creating a maintenance s

  • Trigger to prevent duplicate record names in salesforce 2012-01-30

    I need to prevent duplicate names from been entered. This restriction needs to be imposed using a trigger. I want to know how i can restrict the DML operations from happening. Not sure of the usage of .addError in bulkified code. Set<string> Se

  • preventing duplicate table inserts using jdo in android connected appengine 2012-03-18

    I would like to know how to prevent duplicate inserts when doing an RPC call from an Android client connected to app engine. Below is my code and what I tried at the back-end but when I do this I get an "Internal Server Error". public void createenti

  • doctrine 2 ODM preventing duplicate record 2011-06-17

    Doctrine NOOB here, trying to figure out how to prevent a duplicate record in an embed many property. I have a EmbededDocment like this: <? /** * @EmbeddedDocument */ class Contact { /** * @Id */ private $id; /** * created timestamp * @Date */ pri

  • Preventing Duplicate Table Inserts 2011-06-17

    The database is SQL Server 2008. I have a query which extracts rows from one or more tables and then attempts to insert them into a table variable. I'd like an efficent way to prevent duplicate inserts, so what I came up with was: INSERT INTO @MyTabl

  • Why do I get duplicate record inserted only at the last record? 2011-12-20

    I get a duplicate record from my procedure which inserts 330+ records. But ONLY on the very last record. So in other words the last 2 records are not distinct, they are the same. What is it about this procedure that allows the last record to get dupl

  • Prevent button serverclick firing on every page refresh 2012-02-22

    Anyone know of a way to prevent a button serverClick event from firing on page refresh? Markup: <INPUT id="btnGo" type="button" value="Go" runat="server"> VB.net: Public Sub btnGo_ServerClick(ByVal sender As Object, _ ByVal e As System.EventArg

  • Prevent duplicate records when imprting into access from excel with vba 2013-09-05

    HI to All, I would like help with the following: Currently I import excel data into an existing Access table with VBA. I would like to exclude all duplicate enteries from being appended to the table. I have 3 fields (EmNo,ckNo,ckdate) that must be ch

  • Prevent Duplicate Records in Many to Many Join Table 2015-01-06

    I have a Many to Many relationship between a Member table and an Event table (One member can go to many events and one event can hold many members). I use the recommended join table to properly create the relationship using the PKs from the Member an

  • How to prevent a form from submitting on page refresh? 2010-07-14

    Possible Duplicate: How do I stop the Back and Refresh buttons from resubmitting my form? I have a form that like most forms submits every time the user refreshes the page. Is there any way to prevent this so the form submits ONLY when the submit but

  • Prevent duplicate records in custom object 2011-11-10

    I have a custom object. There are combination of fields like month_c,Project_c,contact_c and role_c which determine the record as unique. I can write a trigger on before insert to check if there are any records with the same combination already exist

  • How to prevent firing of last event after page refresh? 2010-10-09

    Every time I refresh the browser, my button's event handler fires again. How do you prevent this? --------------Solutions------------- One way could be to use an HTTPModule. You can generate a client side GUID, using Javascript, and have that posted

  • Prevent the previous event trigger at Page refresh (F5) in ASP.NET 2011-05-16

    In my ASP.net application ,when am entering an data and hitting a button to save the information and its getting saved in the database and then prompt a success message to the user and then i refreshed the page it show a error message like the below!

  • prevent race conditions in browser JavaScript page refreshes 2011-07-28

    My web page has auto refresh functionality. The auto refresh is implemented using a timer. GInterValId = window.setInterval("AutoRefresh()",interval); The user can also perform some operations by clicking some buttons on the page. The auto refresh fu

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 0.498 (s). 13 q(s)