Is there an elegant solution to prevent duplicate INSERT due to Back_button or Reload

Hello,

I was wondering does anyone here have an elegant and 100% fail safe solution for STOPPING
duplicate INSERT into the Database due to Back_button or Reload on browser being clicked
by the user.

FYI, I have implanted a few solutions via setting a SESSION to be ON after an INSERT is
made and then turned OFF after we arrived at that page through a certain path, but it does
not seem to be 100% fail safe and certainly not elegant.

So I was wondering if there is an elegant and Universal solution to this vexing issue?

ThanX.

Use POST on forms, then redirect after the form is submitted.

This is what I do as well.

Example:

<?php
  // Parse POST data, INSERT to database, whatever
  ...

  // If the above was successful
  if ($success)
  {
    header('Location: success.html');
  }
?>

The redirecting of the page to success.html or whatever page you choose then allows the user to refresh or use the back button without any side effects.

Well I was hoping to avoid Redirect and load the current page.

But I think that Redirect is really the only fail safe solution.

ThanX

You can have it redirect to the existing page, instead of a new page, that will also prevent the back button or the refresh button from re-posting the data. The point is, you need to use the header(‘Location: yourpagehere’); command to prevent the duplicating of data.

this is untested but perhaps something along the lines of…


if (empty($_SESSION['lastPost']) || $_SESSION['lastPost'] != $_POST) {
	if ($db->insert()) {
		$_SESSION['lastPost'] = $_POST;
	}
}

Any attempt to add the same data to the database should simply fail as a duplicate insert request anyway - as long as you are not using an autoincrement key. Since autoincrement keys are seldom required the problem of duplicated inserts should be fairly rare anyway.