简体   繁体   English

在php中生成随机的唯一代码,并创建一个表并将其存储在Mysql中的表中

[英]generate a random unique code in php and create a table and store it in a table in Mysql

我需要帮助来在php中生成一个随机的唯一代码,并创建一个表并将其存储在Mysql中的表中,然后将此随机数提供给想要注册的任何人,之后将为使用该随机生成的数字的人成功注册并对于那些不使用随机数的人来说是不成功的

If you're using PHP 7, it's easy to generate a random string: 如果您使用的是PHP 7,很容易生成一个随机字符串:

$bytes = random_bytes(5); //random. Increase input for more bytes
$code = bin2hex($bytes); // eg: 385e33f741

Before PHP 7, I would generate an alphanumeric code with a function 在PHP 7之前,我将使用一个函数生成一个字母数字代码

function getRandomString($length){
    $chars = 'abcdefghijklmnopqrstuvwxyz0123456789';    
    $result = '';
    while(strlen($result)<$length):
        $result .= $chars{mt_rand(0,strlen($chars)-1)};
    endwhile;
    return $result;
}

To get a 10-character random code, you just call: 要获取10个字符的随机代码,您只需调用:

$code = getRandomString(10);

You can add more characters to $chars , such as capital letters and punctuations if you want those in the generated code 您可以在$chars添加更多$chars ,例如大写字母和标点符号(如果要在生成的代码中使用的话)

this function should do the trick 这个功能应该可以解决问题

function random_Id($length = 6) {
        $id = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
return $id;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM