0

我有一个具有自动增量“id”的表。我在同一个表中有另一列有一个“键”,我希望它基于自动增量“id”。这将确保永远不会有重复的“密钥”。我希望最好有一个 6 个字符的唯一 ID 生成器。我在网上找到了这个,但我愿意接受其他建议。

4

2 回答 2

0
echo $result['id'] . '_' . uniqid('', true);

这将产生类似 1_513c5858c04967.71142475 的东西,前缀 ID_ 将始终基于数据库当然是唯一的

还不够独特吗?

啊,你想要 6 个字符,怎么样:

function randString($length, $charset='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789')
{
    $str = '';
    $count = strlen($charset);
    while ($length--) {
        $str .= $charset[mt_rand(0, $count-1)];
    }

    return $str;
}

  $key = $result['id'] . '_' . randString(6); //this is unique, cause even you get at a chance of a million that you will get 2 same randString(6); you will have always unique prefix ID_ so you will have 1_G7owOq and 2_G7owOq

  //the code below is just an example of how to loop column for unique key and u dont need it :P just maybe someone else needs it.
  while(mysqli_num_rows(mysqli_query($con, "SELECT id FROM table WHERE key = '".mysqli_real_escape_string($con, $key)."'")) > 0) { 
    $key = $result['id'] . '_' . randString(6); 
  }
于 2013-03-10T09:55:37.893 回答
0

然后是我在这里发布您的最后一种方式:

$key = randString(6);
while(mysqli_num_rows(mysqli_query($con, "SELECT id FROM table WHERE key = '".mysqli_real_escape_string($con, $key)."'")) > 0) { 
    $key = randString(6); 
}

它总是会创建随机的 6 个字符键,因为如果它命中 db 中已经存在的键,它将重新创建新的键,依此类推,直到其唯一:] 这是你最好的方式,我也在使用这种方式:]

实际上最好的方法是使用所有现有的唯一键 (62^6) * 每个键 6 个字节 -> 317 GB 如果我没记错的话(早上):] 我不认为你会达到 1/10000其中:]

于 2013-03-11T08:28:35.197 回答