How to generate unique id in MySQL?

前端 未结 16 2620
生来不讨喜
生来不讨喜 2020-11-29 03:17

I\'m programming a script using PHP and MySQL and I want to get a unique id (consisting of a string: capitals and small letters with numbers) like: gHYtUUi5b.

相关标签:
16条回答
  • 2020-11-29 04:10

    crypt() as suggested and store salt in some configuration file, Start salt from 1 and if you find duplicate move to next value 2. You can use 2 chars, but that will give you enough combination for salt.

    You can generate string from openssl_random_pseudo_bytes(8). So this should give random and short string (11 char) when run with crypt().

    Remove salt from result and there will be only 11 chars that should be enough random for 100+ millions if you change salt on every fail of random.

    0 讨论(0)
  • 2020-11-29 04:10

    USE IT

        $info = random_bytes(16);
        $info[6] = chr(ord($info[6]) & 0x0f | 0x40); 
        $info[8] = chr(ord($info[8]) & 0x3f | 0x80); 
        $result =vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($info), 4));
        return $result;
    
    0 讨论(0)
  • 2020-11-29 04:11

    If you use MySQL with version higher than 5.7.4, you can use the newly added RANDOM_BYTES function:

     SELECT TO_BASE64(RANDOM_BYTES(16));
    

    This will result in a random string such as GgwEvafNLWQ3+ockEST00A==.

    0 讨论(0)
  • 2020-11-29 04:12

    You might also consider using crypt()* to generate a [nearly-guaranteed] unique ID inside your contraints.

    0 讨论(0)
提交回复
热议问题