Home > Back-end >  How a unique id should be generated randomly or autoincrement
How a unique id should be generated randomly or autoincrement

Time:07-08

I am generating a unique id auto increment. Is it good? Or should I generate it randomly? which one is better and why?

CodePudding user response:

If you can, implement it using UUIDs. MySQL's UUID() function will return a 36 chars value which can be used for ID.

you can check here there have been the same discussion

How to to create unique random integer ID for primary key for table?

CodePudding user response:

To add a complement of the answer of Amir, this is the code I use to generate a UUID code from PHP (found on stackoverflow) :

  function genUUID(){
    return sprintf( 'xx-x-x-x-xxx',
      // 32 bits for "time_low"
      mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),

      // 16 bits for "time_mid"
      mt_rand( 0, 0xffff ),

      // 16 bits for "time_hi_and_version",
      // four most significant bits holds version number 4
      mt_rand( 0, 0x0fff ) | 0x4000,

      // 16 bits, 8 bits for "clk_seq_hi_res",
      // 8 bits for "clk_seq_low",
      // two most significant bits holds zero and one for variant DCE1.1
      mt_rand( 0, 0x3fff ) | 0x8000,

      // 48 bits for "node"
      mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
    );
  }

this is an example of what I get : 33aaf010-ca70-47fd-877c-00e09bc61697

  •  Tags:  
  • php
  • Related