您可以嘗試生成與第一和姓氏串聯的用戶名。然後使用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