我的代码生成重复ID的可能性有多大?

时间:2014-11-12 09:06:40

标签: php sql random

美好的一天。正如问题所述。下面的代码生成重复ID的可能性有多大?我想知道这个的原因是决定是否应该对整个数据库进行检查以搜索重复项并重新生成新ID(如果有)。如果需要任何额外信息,请与我们联系。也非常欢迎替代品。感谢〜

$query = "SELECT 'ID' FROM world_highscore";
$result = mysql_query($query) or die('Query failed: '. mysql_error());

$num_results = mysql_num_rows($result);

//set of characters to be used in the ID.
$rand_charset = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", 
            "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
            "1", "2", "3", "4", "5", "6", "7", "8", "9", "0");

//the seed is the current number of entries in the table + 1.
$seed = $num_results + 1;

//function to generate and return an ID
function randomizeID($seed, $rand_charset){
    $rand_id = array("0", "0", "0", "0", "0", "0", "0", "0");

    for($i = 0; $i < 8; $i++){
        mt_srand($seed);
        $rand_id[$i] = $rand_charset[mt_rand(0, 35)];

        //not really sure if this is really required but the seed is incremented by one for each 
        //iteration to hopefully introduce more randomization.
        $seed++;    
    }
    return implode($rand_id);                       
}

1 个答案:

答案 0 :(得分:0)

简单替代,

$id = md5(time().rand(1, 999999));