【发布时间】:2014-11-12 09:06:39
【问题描述】:
大家好。正如问题所述。下面的代码生成重复 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);
}
【问题讨论】:
-
字母表中的 35 个字符,8 个字符长。不是
8 ^ 35吗? (这还没有考虑到srand。)所以 4.0564819e+31 个唯一字符串? -
这样很痛。确实如此。除非您知道自己在做什么(通常情况下您不知道),否则不要重新播种 PRNG。如果您想要防碰撞,只需使用 GUID。
-
感谢 GUID 推荐