唯一的Alpha数值生成器 [英] Unique Alpha numeric generator

查看:168
本文介绍了唯一的Alpha数值生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向数据库中的用户提供唯一的字母数字ID。我使用下面的代码,这会总是生成一个唯一的id吗?以下是代码的更新版本:

I want to give our users in the database a unique alpha-numeric id. I am using the code below, will this always generate a unique id? Below is the updated version of the code:

old php:

// Generate Guid 
function NewGuid() { 
    $s = strtoupper(md5(uniqid(rand(),true))); 
    $guidText = 
        substr($s,0,8) . '-' . 
        substr($s,8,4) . '-' . 
        substr($s,12,4). '-' . 
        substr($s,16,4). '-' . 
        substr($s,20); 
    return $guidText;
}
// End Generate Guid 

$Guid = NewGuid();
echo $Guid;
echo "<br><br><br>";

新PHP:

// Generate Guid 
function NewGuid() { 
    $s = strtoupper(uniqid("something",true)); 
    $guidText = 
        substr($s,0,8) . '-' . 
        substr($s,8,4) . '-' . 
        substr($s,12,4). '-' . 
        substr($s,16,4). '-' . 
        substr($s,20); 
    return $guidText;
}
// End Generate Guid 

$Guid = NewGuid();
echo $Guid;
echo "<br><br><br>";

第二个(新PHP)代码将保证100%的唯一性。

Will the second (new php) code guarantee 100% uniqueness.

最终代码:

PHP

// Generate Guid 
function NewGuid() { 
    $s = strtoupper(uniqid(rand(),true)); 
    $guidText = 
        substr($s,0,8) . '-' . 
        substr($s,8,4) . '-' . 
        substr($s,12,4). '-' . 
        substr($s,16,4). '-' . 
        substr($s,20); 
    return $guidText;
}
// End Generate Guid 

$Guid = NewGuid();
echo $Guid;

$alphabet = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';    

function base_encode($num, $alphabet) {
    $base_count = strlen($alphabet);
    $encoded = '';

    while ($num >= $base_count) {

        $div = $num/$base_count;
        $mod = ($num-($base_count*intval($div)));
        $encoded = $alphabet[$mod] . $encoded;
        $num = intval($div);
    }

    if ($num) $encoded = $alphabet[$num] . $encoded;
        return $encoded;
}


function base_decode($num, $alphabet) {
    $decoded = 0;
    $multi = 1;

    while (strlen($num) > 0) {
        $digit = $num[strlen($num)-1];
        $decoded += $multi * strpos($alphabet, $digit);
        $multi = $multi * strlen($alphabet);
        $num = substr($num, 0, -1);
    }

    return $decoded;
}

echo base_encode($Guid, $alphabet); 

}



为了更强大的唯一性,我使用$ Guid作为密钥生成器。

So for more stronger uniqueness, i am using the $Guid as the key generator. That should be ok right?

推荐答案

如果你想让id是唯一的,你应该使用uniqid生成GUID

If you want the id to be unique, you should generate a GUID using uniqid.

您的方法不能保证所有的唯一性。很可能会造成冲突。

Your method will not guarantee uniqueness at all. And will likely create collisions.

这篇关于唯一的Alpha数值生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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