Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only insert if the value doesn't exist

Tags:

php

mysql

+----+----------+-----------+
| id | gamertag | 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."')");
like image 735
AndrewFerrara Avatar asked Feb 17 '26 18:02

AndrewFerrara


1 Answers

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.

like image 78
awm Avatar answered Feb 19 '26 07:02

awm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!