Search code examples
phpuser-registration

Cannot register the new user if the table is empty


$query = "SELECT username, email
              FROM members
              WHERE username = :username OR email = :email";
    $stmt = $sql->prepare($query);
    $stmt->execute(array(
        ':username' => $_POST['username'],
        ':email' => $email
    ));

    $existing = $stmt->fetchObject();

    if ($existing)
    {
        if ($existing->username == $_POST['username'])
        {
            $errors['username'] = "Username already in use !";
        }
        if ($existing->email == $email)
        {
            $errors['email'] = "Mail already in use !";
        }
    }

This is the part of register.php file. Not sure that just this part is responsible for the problem, but I suppose.
So, if table members is empty, and form is submitted - Firefox shows it's busy-gif about a half minute, but ends without registering new user, and without showing any error. Just keep freezing.
Then i press F5 - a window to approve resend information appears - click Resend - and the new user is registered.
If the tablemembersis not empty - everything works normally.
It seems - problem is because the code above is busy to find non-existing data.
If so, how to tell something like - if the table is empty - stop trying - just register the new user.


Solution

  • I'm pretty sure $existing = $stmt->fetchObject(); is fetching you an empty object, but one that does not implicitly evaluate to false. After that there's nothing in your code that would trigger, leading to your blank output.

    Try a var_dump($existing) to see what your code is actually operating on.

    edit

    $existing = $stmt->fetchObject(); //this might be returning an empty object
    
    if ($existing) { //empty objects evaluate to true
        if ($existing->username == $_POST['username']) {
            $errors['username'] = "Username already in use !";
        } else if ($existing->email == $email) {
            $errors['email'] = "Mail already in use !";
        } else {
            //this will trigger if something ELSE is wrong other than what you're explicitly checking for.
            $errors['other'] = "Something else is wrong.\n" . var_export($existing, TRUE);
        }
    }