What I am trying to do is create a 12 character id for articles on my website similar to how youtube handles their video id (http://www.youtube.com/watch?v=53iddd5IcSU). Right now I am generating an MD5 hash and then grabbing 12 characters of it like this:
$ArticleId = substr(MD5("Article".$currentID),10,12)
where $currentID is the numeric ID from the database (eg 144)
I am slightly paranoid that I will run into a duplicate $ArticleId, but realistically what are the chances that this will happen? And also, being that the column in my database is unique, how can I handle this rare scenario without having an ugly error thrown?
P.S. I made a small script to check for duplicates within the first 5000 $ArticleId's and there were none.
EDIT: I don't like the way the base64_encode hashes look so I did this:
function retryAID($currentID)
{
$AID = substr(MD5("Article".$currentID*2),10,12);
$setAID = "UPDATE `table` SET `artID` = '$AID' WHERE `id` = $currentID ";
mysql_query($setLID) or retryAID($currentID);
}
$AID = substr(MD5("Article".$currentID),10,12);
$setAID = "UPDATE `table` SET `artID` = '$AID' WHERE `id` = $currentID ";
mysql_query($setAID) or retryAID($currentID);
Since the AID column is unique the mysql_query will throw an error and the retryAID function will find a unique id...