This is how I check for duplicate Row ID's in my table:
# Generate random Row ID
$rid = rand(1000, 9999);
# start query (yours will be different as I have a class created for starting
# connections with PDO; nonetheless, you should still understand what im doing here)
$query_ridcheck = $db->connect->prepare("SELECT * FROM `table` WHERE rid=:rid");
$query_ridcheck->bindValue(':rid', $rid, PDO::PARAM_STR);
$query_ridcheck->execute();
# if it fetches any data back (while searching for the newly created $rid),
# then generate another random $rid again and check again. This while loop will
# keep going until it DOESN"T fetch any data back (meaning the random $rid has
# not been taken already).
while($query_ridcheck->fetch(PDO::FETCH_ASSOC)){
$rid = rand(1000, 9999);
$query_ridcheck = $db->connect->prepare("SELECT * FROM `table` WHERE rid=:rid");
$query_ridcheck->bindValue(':rid', $rid, PDO::PARAM_STR);
$query_ridcheck->execute();
}
Essentially, you can check for duplicate data before inserting, and choose what todo. I choose to regenerate the data and check again until I got a string/integer that wasn't a duplicate.
After this check, I go onto insert the data into the table using that row ID (since I now know it will not be taken)
Or like @Your_Common_Sense graciously pointed out, instead of repeating code you can also perform the same function like this:
# executes at lease once, then checks if the condition
# is true; If it is, continue looping until it's false.
do{
$rid = rand(1000, 9999);
$query_ridcheck = $db->connect->prepare("SELECT * FROM `table` WHERE rid=:rid");
$query_ridcheck->bindValue(':rid', $rid, PDO::PARAM_STR);
$query_ridcheck->execute();
}while($query_ridcheck->fetch(PDO::FETCH_ASSOC));