jeudi 16 août 2018

Generating Random IDs for Database

I have a requirement on a project where

  • I need to generate unique ID's.
  • ID's must be upper case.
  • I cannot check database to see if ID has been used previously.

We expect to have many millions of records added to database every month.

I have tried solutions here: PHP: How to generate a random, unique, alphanumeric string? and while they seem to work at first, my testing has shown there would be duplicates over time.

Now I am looking at using uniqid with a prefix. The problem I found using uniqid without a prefix is that duplicates will be generated when simultaneous requests come into server at the same exact time. I am hoping using a prefix would solve this.
I am thinking of using this function:

private function generate_id()
{
    $alpha_numeric = 'ABCDEFGHIJKLMNPQRSTUVWXYZ0123456789';
    $max = strlen($alpha_numeric);
    $prefix = '';

    for ($i = 0; $i < 5; $i++)
    {
        $prefix .= $alpha_numeric[random_int(0, $max - 1)];
    }
    return strtoupper(uniqid($prefix));
}

The prefix would be a 5 character alphanumeric string. Would this be enough to satisfy my requirements?




Aucun commentaire:

Enregistrer un commentaire