您如何向PHP中的用户建议唯一的用户名? [英] How do you suggest unique usernames to user in PHP?
问题描述
假设某人想要的用户名被使用,那么我希望系统建议可用用户名的列表,例如5条建议.
Let's say the username someone wants is taken, then I want the system to suggest a list of available usernames, say 5 suggestions.
现在,我可以根据我已有的数据的排列和组合生成多个用户名,例如名称,生日等.但是,如何确保这些生成的用户名可用?我的意思是,如果对于每个生成的用户名,我必须查询数据库以检查可用性,在最坏的情况下,这可能会变成无限循环之类的事情.
Now, I can generate several usernames based on permutations and combinations of data I already have, like their name, birthday, e.t.c. But how do I make sure those generated usernames are available? I mean, if for each generated username, I have to query the database to check availability, in the worst case scenario this might become something like an infinite loop.
有什么想法吗?
推荐答案
我怀疑这个问题是基础问题,因此我将提供一个简单的示例:
I suspect the question is a base one so I'll provide a simple example:
<?php
// Untested code and only one of the many possible ideas
$suggestions = array(
'foobar' => TRUE,
'foo1974' => TRUE,
'foo37' => TRUE,
'drfoo' => TRUE,
'mrfoo' => TRUE,
);
$params = $placeholders = array();
foreach(array_keys($suggestions) as $position => $username){
$params['u' . $position] = $username;
$placeholders[] = ':u' . $position;
}
$sql = 'SELECT username
FROM user
WHERE username IN (' . implode(', ', $placeholders) . ')';
$res = $conn->prepare($sql);
$res->execute($params);
while( $row = $res->fetch(PDO::FETCH_ASSOC) ){
$suggestions[ $row['username'] ] = FALSE;
}
foreach($suggestions as $username => $available){
if($available){
// ...
}
}
提供无限可用名称列表的唯一方法是使用非常简单的规则,例如添加连续数字.在这种情况下,您可以尝试执行以下操作:
The only way to provide an infinite list of available names is to use a very simple rule such as adding a consecutive number. In such case, you can try something like this:
SELECT username
FROM user
WHERE username REGEXP '^foo[0-9]+'
...然后:
$username = 'foo';
$suggestions = array();
$count = 0;
$names_left = 5;
while($names_left>0){
$count++;
if( !in_array($username . $count, $names_taken) ){
$suggestions[] = $username . $count;
$names_left--;
}
}
这篇关于您如何向PHP中的用户建议唯一的用户名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!