Paste only if value does not exist

+----+----------+-----------+
| id | gamertag | timestamp |
+----+----------+-----------+

So I have the table above. I only want to insert gamertag if it does not exist yet. How can i do this?

$gamertag = "l RaH l";
mysql_query("INSERT INTO `gamertags`(`gamertag`)VALUES ('".$gamertag."')");
+3
source share
4 answers

You should do both things: Create a unique index in the gamertag column and use insert ignore.

A unique index prevents the addition of a duplicate row.

The insert ignores prevents the mysql warning from being issued when a duplicate row is not added.

+7
source

The gamertag index column is as unique . Then only the first insert will work. If the same game server exists, it INSERTwill fail.

+3

INSERT IGNORE, mysql dev :)

edit - based on the comments below: ya, you need to have the gamertag column as a unique index.
and those who supported could accept this for "understanding."

edit - update the response completing the response:

$gamertag = "l RaH l";
mysql_query("INSERT IGNORE INTO gamertags(gamertag)VALUES ('".$gamertag."')");

don't forget to specify a unique index-ify column gamertags

+2
source

Insert or update is not available (at least it is not) for MySQL

Look at these works for MySQL: http://bogdan.org.ua/2007/10/18/mysql-insert-if-not-exists-syntax.html

0
source

Source: https://habr.com/ru/post/1790632/


All Articles