插入由8个随机字符组成的唯一字符串

编程入门 行业动态 更新时间:2024-10-17 15:34:19
本文介绍了插入由8个随机字符组成的唯一字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用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个随机字符组成的唯一字符串

本文发布于:2023-11-29 12:34:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646410.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   字符

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!