データベースに保存されている各ユーザーに一意のユーザー名を作成する関数を作成しようとしています。
私の計画は、姓と名を連結してユーザー名を作成し、このユーザー名が使用されているかどうかを確認することでした。データベースに保存するだけでなく、保存していた場合は、末尾に番号を追加します。
たとえば、ConnorAtherton が取得された場合、関数は次に ConnorAtherton1、ConnorAtherton2 を一意のユーザー名が見つかるまでチェックします。
これが関数です(デバッグ用にいくつかのエコーステートメントを追加しました)
function createUserName($username, $counter){
global $fname, $lname;
echo "\t\t\tUsername at Start - " . $username . "\n";
// connect to database
require($_SERVER['DOCUMENT_ROOT'] . "/inc/db.connect.php");
$stmt = $conn->prepare('SELECT * FROM users WHERE username = ?');
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->store_result();
echo "\t\t\tUsername before loop - " . $username . "\n";
if( $stmt->num_rows > 0){
//construct original name and try again
$username = ucfirst($fname) . ucfirst($lname) . $counter;
$counter++;
createUserName($username, $counter);
}
echo "\t\t\tUsername after loop - " . $username . "\n\n";
return $username;
}
これがコンソールに返されるものです
Username at Start - ConnorAtherton
Username before loop - ConnorAtherton
Username at Start - ConnorAtherton1
Username before loop - ConnorAtherton1
Username at Start - ConnorAtherton2
Username before loop - ConnorAtherton2
Username after loop - ConnorAtherton2
Username after loop - ConnorAtherton1
そもそもループ (ConnorAtherton2) の後に正しい値が返されますが、ループの後に 2 番目の値が存在する理由がわかりません。
ConnorAtherton1 を返すので、ConnorAtherton2 を返す必要があります。
どんな助けでも大歓迎です。