我正在使用PHP和MySQL, 我有一个包含3个字段的表((ID,Username,PID)).
我希望PID字段包含8个唯一字符的字符串.
我的解决方案是在PHP中生成随机字符串,并检查其是否存在.如果存在,它将生成另一个字符串.
是否有更好的解决方案可以节省处理时间,例如MySQL触发器或类似的东西?
解决方案这将为您提供8个随机字符串:
substr(str_pad(dechex(mt_rand()), 8, '0', STR_PAD_LEFT), -8);在这里找到: www.richardlord/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: www.richardlord/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个随机字符组成的唯一字符串
发布评论