duplicate data insert in CodeIgniter

荒凉一梦 提交于 2019-11-28 00:26:47
Gustav Bertram

This is the Double Submit Problem.

There are several ways of dealing with it:

  1. The Post / Redirect / Get pattern: Breaks the back button, and it does not keep your user from going back far enough to submit again. Does not handle multiple clicks.

  2. Disable the submit button: Handles multiple clicks some of the time, but does not fix the user going back and submitting again.

  3. Store a token in the session: If you have multiple tabs open in the browser, the token stored in the session may get mixed up. (Note: It may be possible to create browser tab specific cookies using javascript, but I have not tried it myself.)

  4. Change the database to not allow duplicates: The best solution, but also the most effort. If it detects a set of duplicate data, ignore the second request.

  5. Unique transaction id: Described on this PHP hacks page, and on this answer.

  6. Multiple tokens in the session: A variation on option 3. If you store all generated tokens in the session, you don't need to involve the database. The probability of a duplicate is much lower, given that tokens are unique inside a session. Possible problems include the set of tokens growing out of control. Maybe fixable with a limited size stack where you add to the top of the stack, and extra tokens fall off the bottom. Untested.

--

I like the unique transaction id method. It works like this:

  1. Generate a random transaction_id and put it in your web form. It goes along when the user clicks submit.

  2. When you receive the request to add a product, check for the transaction_id in the transaction table.

  3. If the id does not exist in the table, do the transaction, and insert the transaction_id into the table.

  4. If the id does exist in the table, the transaction is already done.

You should also search for [double-submit-prevention] in to see if you can find an even better solution.

Theres a simple solution, you can redirect to some other page after adding product, like:

redirect(base_url(). "yourcontrollername/index");

Doing this will remove the post data and data would not be re-added to database.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!