detect duplicate insert

2019-08-12 01:28发布

Is there an easier way to prevent a duplicate insert after refresh? The way I do it now is to select everything with the all fields except ID as parameters; if a record exists i don't insert. Is there a way to possible detect refresh?

7条回答
甜甜的少女心
2楼-- · 2019-08-12 02:01

Assuming it's a database, you could put a unique constraint on the combination of "all fields except ID" and catch the exception on an insert or update.

查看更多
ら.Afraid
3楼-- · 2019-08-12 02:08

I agree with @Austin Salonen that you should start by protecting the DB with primary keys, unique constraints and foreign keys.

That done, many websites will include some JS behind submit buttons to disable the button immediately before sending on the request. This way, users who double click don't send two requests.

查看更多
【Aperson】
4楼-- · 2019-08-12 02:10

What DB are you using? If it's MySQL, and certain other factors of your implementation align, you could always use INSERT IGNORE INTO .... EDIT: Struck for SQL Server

Alternatively, you could create "handler" pages, e.g. your process looks like this:

  1. User attempts to perform "action"
  2. User is sent to "doAction.xxx"
  3. "doAction.xxx" completes, and redirects to "actionDone.xxx"
  4. ???
  5. Profit!

EDIT: After re-reading your question, I'm going to lean more towards the second solution; by creating an intermediate page with a redirect (usually an HTTP/1.1 303 See Other) you can usually prevent this kind of confusion. Checking uniques on the database is always a good idea, but for the simple case of not wanting a refresh to repeat the last action, this is an elegant and well-established solution.

查看更多
时光不老,我们不散
5楼-- · 2019-08-12 02:11

I think you may want to the EXISTS function. Here's a simple explanation of EXISTS I found through google.

查看更多
我命由我不由天
6楼-- · 2019-08-12 02:15

Like Dereleased said, use a 303-based redirect. Make the form submission use POST and then after saving have it send a 303 header and send them to the post-submit URL via a Location header which will be fetched via GET and a refresh will not be re-posting data.

查看更多
相关推荐>>
7楼-- · 2019-08-12 02:16

It has been a long time since I have done any real web work. But back in the 1.1 days I remember using ids associated with a postback to determine if a refresh had occured.

After a quick search I think this is the article I based my solution from:

http://msdn.microsoft.com/en-us/library/ms379557(VS.80).aspx

It basically shows you how to build a new page class that you can inherit from. The base class will expose a method that you call when you are doing something that shouldn't be repeated on a refresh, and an IsPageRefresh method to track if a refresh has occured.

That article was the basis for alot of variations with similar goals, so it should be a good place to start. Unfortunately I can't remember enough about how it went to really give any more help.

查看更多
登录 后发表回答