Prevent unique constraint violations caused by concurrent inserts
Failure to wrap in a transaction is causing your problem.
do
    compute random number
    BEGIN;
    SELECT ... FOR UPDATE;
    if row exists, then start loop over
    INSERT ...;
    COMMIT;
until success

And don't worry about transaction isolation mode.
Or...
do
    compute random number
    INSERT ...;
until success

with autocommit = ON; no worry about isolation mode.
Or...  Use an AUTO_INCREMENT column -- MySQL will deal with guaranteeing a unique id every time.  (Caveat: A little more code is needed on multi-master topologies.)