Generate a Unique ID using PHP and MYSQL

André Figueira picture André Figueira · Mar 12, 2012 · Viewed 10k times · Source

Hi I am creating a system that processes and ID and a UID, The UID we are generating randomly but I am a little stuck, I need to always generate a UID that does not currently exist in the db as the field is a unique field used on the front end so as not to expose the real ID.

So to recap, I am trying to generate a unique id that does not currently exist in the DB the part I haven't got working is the cross checking in the db so it sometimes will give a number that already exists in the db even though it shouldn't thanks in advance.

This is my code so far:

function uniqueID($table) 
{
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

$possible = '1234567890';
$code = '';
$characters = mt_rand(7,14);
$i = 0;

while($i < $characters) 
{ 

    $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
    $i++;

}

$result = $db->query('
SELECT uniqueID
FROM '.$table.'
WHERE uniqueID = "'.$code.'"
LIMIT 1
');

$totalRows = $result->num_rows;

if(!$result)
{

    return $db->error;

}
else
{

    if($totalRows > 0)
    {

        return uniqueID($table);

    }
    else
    {

        return $code;

    }

}

}