Skip to content
Advertisement

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?

Advertisement

Answer

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?

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement