How do you stop race conditions in MySQL? the problem at hand is caused by a simple algorithm:
what you want is LOCK TABLES
or if that seems excessive how about INSERT IGNORE with a check that the row was actually inserted.
If you use the IGNORE keyword, errors that occur while executing the INSERT statement are treated as warnings instead.