防止重复的SQL条目 [英] Prevent Duplicate SQL entries

查看:113
本文介绍了防止重复的SQL条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要防止重复的SQL文本字段行。也就是说,如果第1行的名称字段已经定义为John Smith,我不希望它能够添加另一个John Smith(与该名称相同)。



我尝试检查插入时是否存在,但问题是,如果您同时打开两个浏览器窗口并单击提交同时,他们将两个检查,检查将清除,然后如果它们足够接近,它们将被插入。



哦,这是一个PHP网站。



谢谢!

解决方案

  CREATE UNIQUE INDEX idxname ON tablename(fieldname); 

添加此索引将确保 fieldname 字段将被记录到 tablename 表中。



您将收到第二个客户端的MySQL错误。您应该在您的PHP代码中处理此问题,并再次放置表单(而不是仅显示错误消息)。



另一种可能性(对于更复杂的位置) LOCK 功能。如果在检查之前锁定表,然后插入记录,并发操作(在第二个浏览器窗口中)将被延迟,直到释放锁。那么记录将被保存,所以第二个PHP脚本将看到它并处理这个位置。


I want to be able to prevent duplicate SQL text field rows. That is, if row 1 has the name field already defined as "John Smith", I don't want it to be able to add another "John Smith" (as common as that name might be).

I tried checking if it existed at time of insertion, but the problem is, if you open up two browser windows at the same time and click submit simultaneously, they'll both check, the check will clear, and then they'll both insert if it's close enough together.

Oh, and this is on a PHP site.

Thanks!

解决方案

CREATE UNIQUE INDEX idxname ON tablename (fieldname);

Adding this index will ensure that no duplicate entries for fieldname field will be recorded into tablename table.

You will get a MySQL error with the second client. You should handle this in your PHP code, and put up the form again (instead of just displaying the error message).

An other possibility (for more complex sitations) is the LOCK functionality. If you lock the table before checking and then you insert your record a concurrent operation (in the second browser window) will be delayed until you release the locks. Then the record will be already saved, so the second PHP script will see it and handle the sitation.

这篇关于防止重复的SQL条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆