简体   繁体   English

防止使用PHP将相同的名称插入MySQL

[英]Prevent Inserting to same names into MySQL using PHP

How can i prevent inserting a value into database if it is already exist with the same name in it? 如果已经存在同名的值,如何防止将其插入数据库? echoing alert that this name already exist for example DATABASE has [MARY, MIKE, JOHN] and then someone tried to INSERT the name [JOHN] again, I want to prevent that from happening, Even if he changed the letter style [JoHn] 回显该名称已经存在的警报,例如DATABASE具有[MARY,MIKE,JOHN],然后有人尝试再次插入名称[JOHN],即使他更改了字母样式[JoHn],我也想防止这种情况的发生

Add a UNIQUE index on the column(s) and make sure the column has a case-insensitive (preferably accent-insensitive too) collation. 在该列上添加UNIQUE索引,并确保该列具有不区分大小写(最好也是不区分重音)的排序规则。 That should do it, I think. 我认为应该这样做。

If you try to SELECT first and see if the name is there, you can run afoul of a "race condition". 如果尝试先选择SELECT并查看名称是否存在,则可能会违反“竞赛条件”。 Basically there's a small amount of time between you running the SELECT and INSERT, and someone else can manage to INSERT the name during that. 基本上,您运行SELECT和INSERT之间的时间很少,其他人可以在此期间插入名称。 It's a small chance, but it's there, and eventually it will bite you. 这是一个很小的机会,但确实存在,最终会咬住你。 You can counteract this with a transaction (be careful about the isolation level your transaction uses), but why bother when an index is so much simpler and easier? 您可以使用事务来抵消它(请注意事务使用的隔离级别),但是当索引变得如此简单和容易时,为什么还要打扰呢? Also, you'll need an index on that column anyway if you want your check to be fast. 另外,如果您希望检查很快,就仍然需要在该列上建立索引。

When defining a table UNIQUE may be specified for a given column so a duplicate entry attempt will result in an error (the INSERT query will fail). 定义表时,可以为给定的列指定UNIQUE ,因此重复输入尝试将导致错误(INSERT查询将失败)。

For example: 例如:

CREATE TABLE `test` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL UNIQUE,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=UTF8;

Normally default collation for a varchar is case insensitive (checking would not be bad however). 通常, varchar默认排序规则不区分大小写(但是,检查不会很糟糕)。


Another option is to first execute a SELECT query to find if a record with the same field value already exists and then perform a second INSERT query if no rows are found or display an error otherwise 另一个选择是先执行SELECT查询,以查找是否存在具有相同字段值的记录,然后如果找不到行,则执行第二次INSERT查询,否则显示错误。

You could also use a trigger: 您还可以使用触发器:

DELIMITER $$
CREATE TRIGGER if_exists BEFORE INSERT ON table_name
FOR EACH ROW
BEGIN
    IF EXISTS(SELECT name FROM table_name WHERE LOWER(name) = LOWER(NEW.name)) THEN
        SIGNAL sqlstate '45000' SET message_text = 'Error! User already exists.';
    END IF;
END$$
DELIMITER ;

Replace table_name with the name of your table and name with the name of the attribute you want to compare. table_name替换为表name ,并将name替换为要比较的属性的名称。 Signals are supported by MySQL 5.5 and above. MySQL 5.5及更高版本支持信号。

插入之前,从表中选择用户名LIKE用户名

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM