简体   繁体   中英

Inserting data in MySQL table only if it doesn't exist already: trouble with INSERT IGNORE

so I've been looking around StackOverflow and the MySQL manual for a while, and I can't seem to solve my problem. What I'm trying to do is simply make my data INSERT function such that it doesn't add anything to my table if it already exists. I saw a few methods: the INSERT IGNORE function, together with a unique index, was the one that seemed the best for me, but I have no idea why it is not working... Here is a portion of my code (I have two columns: 'username' and 'email', and my table is called 'info4'):

$unique_index = mysqli_query ($con, "CREATE UNIQUE INDEX index ON info4 ( username, email);");

$insert = mysqli_query($con, "INSERT IGNORE INTO info4 (`username`, `email`) VALUES ('$array_values[0]', '$array_values[1]')");

Where am I going wrong? Am I missing anything?

You can't create an index named index.

Mysql is not case sensitive. Your INDEX wrongly named "index" won't work.

Example:

mysql> create index index on tbladresse (strasse_zusatz); ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'index on tbladresse (strasse_zusatz)' at line 1

mysql> create index iindex on tbladresse (strasse_zusatz); Query OK, 0 rows affected (0.03 sec) Records: 0 Duplicates: 0 Warnings: 0

Insert Ignore simply tells MySQL to not issue a duplicate key error when trying to insert duplicate data into fields with unique constraints.

The unique index should be all you need to stop duplicate entries from being inserted.

Generally you wouldn't want to do things like add indexes using PHP, you should do that via whatever tool you are using to access your database.

Are you seeing duplicate username/email combos being inserted into your table? What are the values of $array_values[0] and $array_values[1] ?

If you do SHOW INDEX FROM info4 do you see your unique index?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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