데이터베이스에 저장된 각 사용자에 대해 고유 한 사용자 이름을 만드는 함수를 만들려고합니다.재귀 PHP 함수가 예상 값을 반환하지 않습니다.
나의 계획은 이름과 성을 연결하여이 사용자 이름이 사용되었는지 확인하는 것입니다. 데이터베이스에 저장하는 것이 아니라면 그 번호 끝에 숫자를 추가하십시오.
예를 들어 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
그것은 루프 후 올바른 값을 반환에 반환 것입니다 (I 디버깅에 대한 몇 가지 에코 문을 추가 한) ConnorAtherton2 수있는 기능입니다)로 시작하지만 왜 루프 뒤에 두 번째 값이 있을지 모르겠다.
ConnorAtherton1을 반환하고 ConnorAtherton2를 반환해야합니다.
도움을 주시면 대단히 감사하겠습니다.
아마 당신이 찾고있는 대답은 아니지만,'WHERE username LIKE "ConnorAtherton %"'을 사용하고 마지막 숫자를 부분 문자열로 바꾸고 1을 더하기 위해 SQL을 변경하는 것에 대해 생각할 것입니다. – Julien