Only insert if the value doesn't exist
+----+----------+-----------+
| id | gamerta开发者_如何转开发g | timestamp |
+----+----------+-----------+
So I have the table above I want to only insert a gamertag if it doesn't already exist. How could I do that?
$gamertag = "l RaH l";
mysql_query("INSERT INTO `gamertags`(`gamertag`)VALUES ('".$gamertag."')");
You should do both things: Create a unique index on column gamertag and use insert ignore
.
The unique index prevents a duplicate row from being added.
The insert ignore prevents mysql from issuing a warning when the duplicate row is not added.
Index gamertag column as unique. Then only thefirst insertion will work. If the same gamertag exists, the INSERT
will fail.
you could try INSERT IGNORE
, check mysql dev pages about this keyword :)
edit - based on the comments below : ya, you need to have gamertag column as a unique index..
and those who upvoted might have taken this for "understood".
edit - updating the answer finalizing the answer :
$gamertag = "l RaH l";
mysql_query("INSERT IGNORE INTO gamertags(gamertag)VALUES ('".$gamertag."')");
don't forget to unique index-ify the gamertags column
Insert or update is not available (at least it was not) for MySQL
Look at these work around for MySQL: http://bogdan.org.ua/2007/10/18/mysql-insert-if-not-exists-syntax.html
精彩评论