错误:关键“电子邮件"的重复条目“"

2022-01-05 00:00:00 mysql phpmyadmin

我以前在运行 php 脚本的人身上看到过这个错误,但这在 phpmyadmin 中发生在我身上 ??

I have seen this error with people running php scripts before but this is happending to me in phpmyadmin ??

Error
SQL query:

UPDATE  `cl56-goldeng`.`users` SET `email` =  '' WHERE  `users`.`id` =118

MySQL said: Documentation

#1062 - Duplicate entry '' for key 'email' 

如果我为该字段指定另一个值,它工作正常,但如果我清除该字段并按 Enter 键,则会出现上述错误.

It works fine if I give the field another value, but if I clear the field and press enter I get the above error.

表格本身看起来像这样:

The table itself looks like this :

推荐答案

在你的表 cl56-goldeng.users 上,字段 email 在创建时被指定为不允许允许超过 1 个相同的值.这是在 MySQL 中创建表时使用 UNIQUE 标识符完成的.您可以在此链接中查看有关 UNIQUE 标识符的更多信息.

On your table cl56-goldeng.users, the field email was specified on creation to not allow more than 1 of the same value to be allowed into it. This is done using the UNIQUE identifier on table creation in MySQL. You can see more on the UNIQUE identifier at this link.

您有 2 个选项可以做.

You have 2 options that you could go about doing.

  • 首先是删除 email 字段上的唯一约束.这完全取决于您在代码中的逻辑,但鉴于电子邮件应该几乎始终是唯一的,因此不建议这样做.
  • First would be to remove the unique constraint on the email field. This entirely depends on your logic in your code, but seeing as emails should almost always be unique, this is not suggested.

您可以通过运行以下命令删除唯一键:alter table [table-name] drop index [unique-key-index-name];

You can drop a unique key by running the command: alter table [table-name] drop index [unique-key-index-name];

  • 其次,将使用 NULL 而不是空字符串.我的假设是,当用户电子邮件不存在时,您正在设置一个空字符串.在这种情况下,最好使用 NULL,然后在从数据库检索数据时检查它.
  • Second, would be to use NULL instead of an empty string. My assumption is that you are setting an empty string when the users email does not exist. In this scenario, it would be better to use NULL, and then check for that when retrieving data from the database.

您可以在 MySQL 语句中使用 NULL 标识符插入 NULL 值,如下所示:

You can insert a NULL value by using the NULL identifier in your MySQL statement, like such:

INSERT INTO users (firstName,lastName,email)
  VALUES ('Bob','Ross',NULL);

然后在您访问此数据的任何语言中检查 NULL 值.

And then check for a NULL value in whatever language you are accessing this data from.

相关文章