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

后端 未结 8 2078
庸人自扰
庸人自扰 2020-12-30 08:50

I was wondering if anybody knew a good way to create a unique random integer id for a primary key for a table. I\'m using MySQL. The value has to be integer.

相关标签:
8条回答
  • 2020-12-30 09:31

    There is an AUTO_INCREMENT feature. I would use that.

    See here more examples.

    0 讨论(0)
  • 2020-12-30 09:33

    my way, for both 32bit and 64bit platform. result is 64bit

    function hexstr2decstr($hexstr){
        $bigint = gmp_init($hexstr, 16);
        $bigint_string = gmp_strval($bigint);
        return $bigint_string;
    }
    
    function generate_64bitid(){
        return substr(md5(uniqid(rand(), true)), 16, 16);
    }
    
    function dbGetUniqueXXXId(){
        for($i = 0; $i < 10; $i++){
            $decstr = hexstr2decstr(generate_64bitid());
    
            //check duplicate for mysql.tablexxx
            if($dup == false){
                return $decstr;
            }
        }
        return false;
    }
    
    0 讨论(0)
提交回复
热议问题