Re: How can I fix that

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Aalee wrote:
> I did a form to add data to a database and it works fine. Once the data is
> entered its gives a thankyou message. But the problem is, if I refresh
> this
> thankyou page, the data is entered again into the database. Why is it
> doing
> so. I couldnt think of a way to fix it. Help...

If one reloads a page in the browser, then, by definition, the browser is
going to send the exact same request to the server again.

So if that request caused you to insert a record to the database, it
should be no surprise if a repeat of that exact same request causes you to
do that again. :-)

As to ways to solve this, probably the cleanest is to add an
<INPUT TYPE="HIDDEN" NAME="no_repeat" VALUE="<?=md5(uniqid())?>">

Then, when you insert the record, also insert $no_repeat into a new table:
create table no_repeat(
  no_repeat char(32),
  whattime timestamp
);

Then, before you do an INSERT to your main table, you do a:
SELECT count(*) from no_repeat where no_repeat = '$no_repeat'

If that returns 1 for the count (use http://mysql_result or
http://php.net/mysql_fetch_row or http://mysql_fetch_array or...) then you
know that this form was already submitted.

It also helps to use METHOD="POST" in your FORM tag, because then most
browsers will prompt the user before they go submitting the same stuff
twice with re-load -- whereas METHOD="GET" sort of implies that they can
surf directly to the URL or reload to repeat the action.

Which, sometimes, you actually *want* to allow, by the way.

You also want to run a cron job to routinely
delete from no_repeat where what time <= date_sub(now() , interval 48 hours)
so that you don't clutter up your database with really old crap.

Change 48 hours to whatever you think is suitable, of course.

Using a header("Location: ") will A) not solve the problem if they hit
reload fast enough, and B) is *BAD* *PROGRAMMING* and abusive of the
Location: header in the first place.

If the data being presented should, in theory, be unique, you can also
simply do a SELECT on the data present to see if you already have that
record in the database, and if you do, ignore the request to insert it
again.

-- 
Like Music?
http://l-i-e.com/artists.htm

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux