I have this code below that supposedly will detect duplicate id generation and will not execute. Is this code good enough to prevent duplicate ids?
//$guid and $alphabet are other sources from which id is generated
$unique = false;
while($unique == false){
$Guid = NewGuid();
ob_start();
echo base_encode($Guid, $alphabet);
$newid = ob_get_contents();
ob_get_clean();
$query = "SELECT * FROM posts WHERE id='$newid'";
$res = mysql_query($query) or die(mysql_error());
if(mysql_num_rows($res) == 0)
$unique = true;
}
The best approach would be to allow MySQL to create the IDs using auto_increment.
Then you just insert without specifying the ID column. To retrieve the value, use
mysql_insert_id().If there is some valid reason you can’t use auto_increment (you have no control over the database and have been told no at least a hundred times by at least 10 IT people), then the next solution would be to add a unique index on the column, which would prevent entering a duplicate.
This will prevent any duplicates. If an attempt to insert fails because of a unique key being violated (which will be in the error message), you can simply retry the insert with a new GUID.
Collisions will be rare enough (near impossible) that you don’t really have to worry about optimizing this unless there will be tens of millions of records (probably hundreds of millions).
There aren’t going to be many other good options that can avoid a race condition. You can manage it with transactions, but it’s going to be very, very tricky at your current level of understanding and in almost all cases a waste of your time given these two options above.
So I guess to summarize, the specific answer to the question you posited is probably to just try and insert it. If you get a dup, ask for a new ID and try again. But there are probably better strategies depending on your use case.