H
H
HellCode2021-12-20 19:32:12
AJAX
HellCode, 2021-12-20 19:32:12

How to check if a nickname is busy?

The essence of the problem is that there is a user registration source (the source is not mine)
I can’t implement the function .. check if there is such a username in the database or not.
If there is - continue registration, if not - an error that the user exists.
At the same time, there is a find function in the source code where email is checked (it works), I tried to play with it, but nothing comes out.

public static function find($email, $return_assoc = false){
        $con = DB::getConnection();
        $email = (String) Filter::String( $email );
        // Make sure the user does not exist. 
    $findUser = $con->prepare("SELECT user_id,password FROM users WHERE email = LOWER(:email) LIMIT 1");
    $findUser->bindParam(':email', $email, PDO::PARAM_STR);
        $findUser->execute();

        if ($return_assoc) {
            return $findUser->fetch(PDO::FETCH_ASSOC);
            # code...
        }
        $userFound = (boolean) $findUser->rowCount;
         return $userFound;
    }


handler:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Always return JSON format
    // header('Content-Type: application/json');

    $return = [];
    
    $username =  Filter::String( $_POST['username'] );

    $email = Filter::String( $_POST['email'] );
    
    $userFound = User::find($email, true);

    if($userFound) {
      // User exists 
      // We can also check to see if they are able to log in. 
      
      
      $return['error'] = "You already have an account";
      $return['is_logged_in'] = false;
    } else {
      // User does not exist, add them now. 
      
      $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
      
      
      $addUser = $con->prepare("INSERT INTO users(username, email, password) VALUES(LOWER(:username), :email, :password)");
      $addUser->bindParam(':username', $username, PDO::PARAM_STR);
      $addUser->bindParam(':email', $email, PDO::PARAM_STR);
      $addUser->bindParam(':password', $password, PDO::PARAM_STR);
      $addUser->execute();

      $user_id = $con->lastInsertId();

      $_SESSION['user_id'] = (int) $user_id;

      $return['redirect'] = '../index.php';
      $return['is_logged_in'] = true;
    }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question