1

I have a function that imports a files contents into mySQL and returns the results. If i refresh the page and click "yes" it will do it again doubling the output with the same content.

How can I stop this happening? In this particular case there is no URI in the address bar but on other functions there is.

Nicekiwi
  • 4,567
  • 11
  • 49
  • 88

4 Answers4

2

You should just check if the contents in the database exist, if they don't, fill them. Otherwise don't run the function.

psuedo-code:

if !database.containsRecords
  fillDatabase()
end

On top of this, it is always good practice to redirect after a POST request. So you would want:

fillDatabase();
header("Location page.php");
exit();
Mike Lewis
  • 63,433
  • 20
  • 141
  • 111
1

Query the database on each page load and see if it has already been populated. If it has been populated then don't attempt to populate it again.

Treffynnon
  • 21,365
  • 6
  • 65
  • 98
1

You should use the POST-redirect-GET pattern.

After updating the database, send an HTTP redirect to a separate page that displays the results.
Refreshing the browser will reload that separate page.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • And using the browser back button will mess up anyway. Yes some modern browsers prevent resending POST data but not all. – Oliver A. Apr 17 '11 at 15:58
  • Yup you really should do a redirect on success. Actually you should do this for all forms. It is best practise. – PeeHaa Apr 17 '11 at 16:00
  • @Oliver: Wrong. Redirects do not create separate entries in history; going back will go back to the page that submitted the form. – SLaks Apr 17 '11 at 16:03
  • Yes if you do it right. Some redirects DO create entities and sometimes bad redirects even trap you on a page. – Oliver A. Apr 17 '11 at 16:11
  • @Oliver: Javascript redirects (`location.href = ...`) can cause history entries, and HTML meta-refresh bounces could (not sure on that one). HTTP 30x redirects generally don't (except on exceptionally poorly-written browsers, none of which are in common use). – cHao Apr 17 '11 at 16:17
0

I assume you use a POST form to upload the file. You can include a hidden input field with an pseudo random unique id in your form. If the user resends the data via POST you can check if you already processed this request. Hidden fields are not save because a user might edit them, but you can detect accidental resubmits.

Oliver A.
  • 2,870
  • 2
  • 19
  • 21