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

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

问题描述

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

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.

哦,这是在 PHP 网站上.

Oh, and this is on a PHP site.

谢谢!

推荐答案

CREATE UNIQUE INDEX idxname ON tablename (fieldname);

添加此索引将确保 fieldname 字段的重复条目不会记录到 tablename 表中.

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

第二个客户端会出现 MySQL 错误.您应该在您的 PHP 代码中处理这个问题,然后再次提交表单(而不仅仅是显示错误消息).

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).

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

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天全站免登陆