Search code examples
phpmysqluidunique-id

Generate a Unique ID using PHP and MYSQL


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;

    }

}

}

Solution

  • I figured out what the problem was already, As I mentioned to everyone the code generation was not the issue! The issue was that the cross check was not working correctly. So all I did was removed this loop

    while($i < $characters) 
    { 
    
        $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
        $i++;
    
    }
    

    As this was causing my unique ID to end up wrong.