防止重复的 SQL 条目

2023-12-01php开发问题
6

本文介绍了防止重复的 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 条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

PHP实现DeepL翻译API调用
DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以...
2025-08-20 php开发问题
168

PHP通过phpspreadsheet导入Excel日期数据处理方法
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的...
2024-10-23 php开发问题
287

mediatemple - 无法使用 codeigniter 发送电子邮件
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)...
2024-08-23 php开发问题
11

Laravel Gmail 配置错误
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)...
2024-08-23 php开发问题
16

将 PHPMailer 用于 SMTP 的问题
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)...
2024-08-23 php开发问题
4

关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)...
2024-08-23 php开发问题
17