Home > Software engineering >  generating unique id's instead of using mysql auto_increment for different tables
generating unique id's instead of using mysql auto_increment for different tables

Time:01-19

So I have at least 10 tables with autoincrement the only unique column is email but don't wanna use them as users might wanna change them later so my question.

How good is a guid function like this to use and forget to generate unique IDs?

function guidv4($data = null) {
   
    $data = $data ?? random_bytes(16);
    assert(strlen($data) == 16);

    $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
    
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80);

    return vsprintf('%s%s%s%s%s%s%s%s', str_split(bin2hex($data), 4));
}

or should I check database for collision every now and then ?

or should I use MySQL UUID ?

CodePudding user response:

There are two ways you could go about this.

The simplest and probably the best way being the MySQL uuid function. However, you could also use the last inserted id to generate a UUID, as long as it guarantees an ID that is actually unique, it is however very easy to get this wrong.

CodePudding user response:

A data that you create with a unique id in PHP can sometimes give the same output. The solution is in the link below. You can generate unique values.

https://www.php.net/manual/en/function.uniqid.php#120123

  •  Tags:  
  • Related