Is it possible to use PHP "if" statements in SELECT query results to determine whether to execute an INSERT query and override unintended data?

I am a student and this is the first time I am writing a piece of software. This is a web application in the LAMP stack, and as part of this web application I wrote the following function to interact with the database when creating a new user:

public function CreateUser($username, $password, $email){
  global $DBHandler, $SQLStatement;
  $SQLStatement = $DBHandler->prepare("SELECT id FROM users WHERE username = :username AND verified > 0");
  $SQLStatement->bindParam(':username', $username);
  $SQLStatement->execute();
  $check = $SQLStatement->fetch();
  if ($check['id']){
    return 2;
  }else{
    $SQLStatement = $DBHandler->prepare("SELECT id FROM users WHERE email = :email AND verified > 0");
    $SQLStatement->bindParam(':email', $email);
    $SQLStatement->execute();
    $check = $SQLStatement->fetch();
    if ($check['id']){
      return 3;
    }else{
      /* Edited out code that generates a random verification code, a random salt, and hashes the password. */
      $SQLStatement = $DBHandler->prepare("INSERT INTO users (username, email, passwordhash, salt, verifycode) VALUES (:username, :email, :passwordhash, :salt, :verifycode)");
      $SQLStatement->bindParam(':username', $username);
      $SQLStatement->bindParam(':email', $email);
      $SQLStatement->bindParam(':passwordhash', $passwordhash);
      $SQLStatement->bindParam(':salt', $salt);
      $SQLStatement->bindParam(':verifycode', $verifycode);
      $SQLStatement->execute();
      return 1;
    }
  }
}

$ DBHandler is triggered elsewhere as a PHP data object.

This follows from the following basic steps:

  • Request a database to verify that someone has already verified the account with the desired username.
  • If the username is available, run another request and perform the same check for email.
  • , , , , -, , 1 ( ).

, , (verified = '1'). script, "1", .

:

A "Lorem" , B , "Lorem" . , ?

  • A script , "Lorem"
  • B script "Lorem"
  • A script "Lorem"

:

3 script 1 if/else, SQL PHP, , /

+5
1

insert :

insert  into users 
        (username, email, ...)
select  :username, :email, ...
where   not exists
        (
        select  *
        from    users
        where   verified > 0
                and (username = :username
                     or email = :email)
        )

100% MySQL, .

, concurrency - . , ​​ , , !

+2

All Articles