忽略不工作Mysql



嗨,我正在通过脚本导入csv文件表结构如下

`contact_id` int(11) NOT NULL auto_increment,
  `contact_first` varchar(255) character set latin1 default NULL,
  `contact_last` varchar(255) character set latin1 default NULL,
  `contact_email` varchar(255) character set latin1 default NULL,
  PRIMARY KEY  (`contact_id`)

CSV格式的数据是这样的

Jim,Smith,jim@tester.com
Joe,Tester,joe@tester.com

和我使用的插入查询如下所示

mysql_query("INSERT IGNORE INTO contacts (contact_first, contact_last, contact_email) VALUES
                (
                    '".addslashes($data[0])."',
                    '".addslashes($data[1])."',
                    '".addslashes($data[2])."'
                )
            ");

我在查询中使用了忽略函数,但它不起作用,它继续保存相同的值

IGNORE关键字只会对重复的行产生您想要的影响。

只有在相应的列上有主键或唯一键时,行才会被识别为重复。

您还没有真正解释问题是什么,但我怀疑您可能想要在contact_email列上创建一个唯一的键,以防止重复项被插入。

我还建议至少使用mysql_escape_string而不是addslashes来确保字符串被正确编码。

可能会有关于mysql_*函数被弃用的事实的注释,所以你应该查看PDO或mysqli_*函数

如果使用IGNORE关键字,则在执行INSERT语句时发生的错误将被视为警告参考文档

忽略:

If you use the IGNORE keyword, errors that occur while executing the INSERT statement are treated as warnings instead. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. With IGNORE, the row still is not inserted, but no error is issued.

在您的情况下,您正在插入三个相同的值,但由于ID是auto incremental,这将插入具有相同值的新记录,这是显而易见的。如果你想防止它插入到数据库中你必须为另一列添加唯一索引

希望对你有帮助!

最新更新