Question

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;

    }

}

}
Was it helpful?

Solution 6

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.

OTHER TIPS

To generate unic UID you can use time, i think it was a very small chanse that records will be added in the same second, with two random data.

write some function which return it to you like that

function generate_uid(){
 return md5(mktime()."-".rand()."-".rand());
}

In PHP there's a function called uniqid()

http://php.net/manual/en/function.uniqid.php

I could talk about generating ids, like the others did, but this is not your question. Your query seems fine. If it returns 0 rows but you seem to find the code in the database, then most likely it only looks the same, but actually isn't. It could be padded by whitespace.

One way to solve this is by selecting the last row of your user database and have your script to check for the id field (you can achieve this by performing a select ordering by ID in descendent mode) then you can use that info for randomize numbers greater than that ID.

EDIT

$result = $db->query('
SELECT uniqueID
FROM '.$table.'
');

$already_in_database = array();
while ($row = mysql_fetch_array($result)){
    $already_in_database[] = $row['UID'];    
}

$new = rand(0,$some_max_value);
while(in_array($new,$already_in_database)){
    $new = rand(0,$some_max_value);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top