您可以尝试生成与第一和姓氏串联的用户名。然后使用MySql中的LIKE
子句查找任何匹配的用户名。这将生成一组完全匹配或像自动生成的用户名的用户名。然后,您可以遍历该数组,直到您自动生成数据库中不存在的用户名。
在PHP中看起来像这样。
// The $suffix is the number to add if the username exists. The default is NULL/nothing
$suffix = null;
// Auto-generate the username.
$username = generate_username_function($firstname, $lastname, $suffix);
// Instantiate a new PDO instance.
$pdo = new PDO('mysql:host=...', $db_username, $db_password); // Insert your DNS string here.
// Build the SQL query.
$query = "
SELECT username
FROM users
WHERE username LIKE ':username%'
";
$statement = $pdo->prepare($query);
$statement->bindParam(':username', $username, PDO::PARAM_STR);
if(!$statement->execute()) {
// throw an exception if the query couldn't be executed.
}
$existing = $statement->fetchAll(PDO::FETCH_ASSOC);
// Loop through the existing usernames to check if the auto-generated username exists.
// Set an $available flag on indicate when the username is available.
$available = false;
$current = 1;
$ceiling = 1000; // This is to avoid infinite loops. Increase this if necessary.
while(!$available) {
// Check if the loop ceiling has been reached.
if($current == $ceiling) {
// throw an exception(preferred) or emit an error.
}
if(!in_array($username, $existing)) {
$available = true;
}else{
if(is_null($suffix)) {
$suffix = 1;
}else{
$suffix++;
}
$username = generate_username_function($firstname, $lastname, $suffix);
}
$current++;
}
这将继续递增后缀,直到找到可用的用户名。可以改进用户名的生成,但我会将其留给您:D
现在您有一个可用的用户名,您可以将其与任何其他信息一起存储在数据库中。
此致敬礼。
你或许应该立足于一个auto_incremented ID添加的数量(INT)柱,并增加它基于这一点。 *想想outloud * – 2014-11-20 16:57:01
@ Fred-ii-:你的意思是,如果用户名已经存在,那么我需要用当前的自动增量ID联系用户名? – 2014-11-20 16:58:39
准确地说,所有在条件语句中设置。这就是我要做的。 – 2014-11-20 16:59:25