PHP/MySQL-创建唯一随机字符串的最佳方法? [英] PHP/MySQL - Best way to create unique random string?

查看:69
本文介绍了PHP/MySQL-创建唯一随机字符串的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在MySQL中创建随机的唯一字符串?

How do I create a random unique string in MySQL?

当我需要在PHP中创建随机字符串时,可以使用以下功能:

when I need to create a random string in PHP I use this function:

public function generateString($length)
{   
    $charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    for($i=0; $i<$length; $i++) 
        $key .= $charset[(mt_rand(0,(strlen($charset)-1)))]; 

    return $key;
}

然后,我将生成的字符串存储在MySQL数据库中.

Then I would take the generated string and store it in a MySQL database.

确保生成的随机字符串对于为数据库中其他条目创建的所有其他随机字符串唯一的最佳方法是什么?

What is the best way to make sure the generated random string is unique to all the other random strings created for other entries in the database?

也许是这样吗?

while(++$i < 100)
{
  //query db with random key to see if there is a match

  //if no match found break out of loop
  break;

}

这看起来很混乱而且很长,我可能会多次访问数据库.如何快速确定我的新随机字符串是唯一的?

This seems messy and long, and I could potentially hit the database multiple times. How can I quickly be sure my new random string is unique?

推荐答案

假设字符集a-z, A-Z, 0-9中有10个字符,则意味着(26 + 26 + 10) 10 = 8.39299366×10 17 可能的组合.要计算碰撞的几率...只需上述数字的1/x.因此,我不必担心两次获得相同的字符串.即使再次获得相同的字符串,我也将再次循环运行该函数,唯一的退出条件是找到了唯一的字符串.

Assuming 10 characters from the character set a-z, A-Z, 0-9 mean there are (26 + 26 + 10)10 = 8.39299366 × 1017 possible combinations. To calculate the odds of a collision... just 1/x the afore-mentioned number. So I would not be worrying about getting the same string twice. Even if do get the same string again I'll just run the function again in a loop, the only exit condition being that a unique string is found.

这篇关于PHP/MySQL-创建唯一随机字符串的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆