插入由8个随机字符组成的唯一字符串 [英] Insert unique strings of 8 random characters

查看:107
本文介绍了插入由8个随机字符组成的唯一字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PHP和MySQL, 我有一个包含3个字段的表((IDUsernamePID)).

我希望PID字段包含8个唯一字符的字符串.

我的解决方案是在PHP中生成随机字符串,并检查其是否存在.如果存在,它将生成另一个字符串.

是否有更好的解决方案可以节省处理时间,例如MySQL触发器或类似的东西?

解决方案

这将为您提供8个随机字符串:

substr(str_pad(dechex(mt_rand()), 8, '0', STR_PAD_LEFT), -8);

在这里找到: http://www.richardlord.net/blog/php-密码安全性

或者如果用户名字段是唯一的,您还可以使用:

substr(md5('username value'), 0, 8);

尽管这是极不可能的,尤其是对于md5,但这两种情况都不保证唯一的字符串,所以我可能会做这样的事情:

// Handle user registration or whatever...

function generatePID($sUsername) {
    return substr(md5($sUsername), 0, 8);
}

$bUnique = false;
$iAttempts = 0;

while (!$bUnique && $iAttempts < 10) {
    $aCheck = $oDB->findByPID(generatePID("username value")); // Query the database for a PID matching whats generated
    if (!$aCheck) { // If nothing is found, exit the loop
        $bUnique = true;
    } else {
        $iAttempts++;
    }
}

// Save PID and such...

...这可能只会产生1个检查"查询,在特殊情况下可能会产生2个查询,并确保一个唯一的字符串.

I'm using PHP and MySQL and I have a table with 3 fields ((ID, Username, PID)).

I want the PID field to contain strings of 8 unique characters.

My solution is to generate the random string in PHP and check if it exists. If it exists then it will generate another string.

Is there any better solution that will save processing time, like a MySQL trigger or something like that?

解决方案

This will give you a random 8 character string:

substr(str_pad(dechex(mt_rand()), 8, '0', STR_PAD_LEFT), -8);

Found here: http://www.richardlord.net/blog/php-password-security

Or if the username field is unique you could also use:

substr(md5('username value'), 0, 8);

Though it's extremely unlikely, particularly for the md5, neither case guarantees a unique string, so I would probably do something like this:

// Handle user registration or whatever...

function generatePID($sUsername) {
    return substr(md5($sUsername), 0, 8);
}

$bUnique = false;
$iAttempts = 0;

while (!$bUnique && $iAttempts < 10) {
    $aCheck = $oDB->findByPID(generatePID("username value")); // Query the database for a PID matching whats generated
    if (!$aCheck) { // If nothing is found, exit the loop
        $bUnique = true;
    } else {
        $iAttempts++;
    }
}

// Save PID and such...

... which would probably only yield 1 'check' query, maybe 2 in unique cases, and would ensure a unique string.

这篇关于插入由8个随机字符组成的唯一字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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