0

I need to have a system where a random password and username are created for each new user.

As such, I need to make sure the username is unique.

However I cant figure out why the code below isn't working. It isn't a syntax issue. I just can't figure out where I have gone wrong logically.

anyway here is what I have tried:

    $Password= randomPassword();
    $Username = randomPassword();
    $UsernameCheckQuery = mysql_query("SELECT * FROM users WHERE username = '".$Username."'");
    while (mysql_num_rows($UsernameCheckQuery ) >= 1) {
        $Username = randomPassword();
        $UsernameCheckQuery = mysql_query("SELECT * FROM users WHERE username = '".$Username."'");
      }

I know this topic appears elsewhere on Stack Overflow and on the web. However every question I have seen has been using an if statement to check if the username is already used. In my case I cant see how an if statement would work as the randomPassword function could generated two username that already exist in a row.

7
  • 2
    for one you should probably use a do while loop. php.net/manual/en/control-structures.do.while.php Commented Nov 21, 2013 at 3:54
  • @IgnacioVazquez-Abrams I dont think it is. Please see me question about if statements Commented Nov 21, 2013 at 3:57
  • 3
    It is exactly a duplicate. Don't check if the username already exists, check if the attempt to insert the row failed. Commented Nov 21, 2013 at 4:01
  • @IgnacioVazquez-Abrams ahh that makes sense - Thanks I believe this question is a duplicate how do i specify that Commented Nov 21, 2013 at 4:05
  • 1
    I don't thinks it's a dup. OP doesn't want to abort if id exists. He wants to keep trying until success. Commented Nov 21, 2013 at 4:11

1 Answer 1

1

Try

while (true) {
    $Username = randomPassword();
    $UsernameCheckQuery = mysql_query("SELECT * FROM users WHERE username = '".$Username."'");
    if (mysql_num_rows($UsernameCheckQuery ) < 1) {
       break;
    }
}
echo 'The generated username is '.$Username;
Sign up to request clarification or add additional context in comments.

1 Comment

works perfectly just syntax error for break; and logic error <

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.