Check record exists db - error show

后端 未结 3 1731
[愿得一人]
[愿得一人] 2021-01-27 07:04

How do I check if username or email exists and then put a error message in my error array. Right now i have:

$sql = \"SELECT username, email FROM users WHERE use         


        
3条回答
  •  遥遥无期
    2021-01-27 07:16

    Sounds like you're trying to let users know whether a username or email already exists at registration time. Here's what you can do:

     0){
    
       //----------------------------------------
       // Username already exists
       $error[] = 'Username already exists';
    
       //----------------------------------------
       // Return error to user and stop execution
       // of additional queries/code
    } else {
    
      //----------------------------------------
      // Check if email exists
    
      //----------------------------------------
      // Create query
      $emailQuery = 'SELECT email FROM users WHERE email="'.mysql_real_escape_string($email).'"';
    
      //----------------------------------------
      // Query the db
      $emailResult = mysql_query($emailQuery);
    
      //----------------------------------------
      // Check if the result is empty
      if(mysql_num_rows($emailResult) > 0){
    
         //----------------------------------------
         // Email already exists
         $error[] = 'Email already exists';
    
         //----------------------------------------
         // Return error to user and stop execution
         // of additional queries/code
      } else {
    
         //----------------------------------------
         // Continue with registration...
      }
    }
    ?>
    

    Please note that you should always escape your values before executing the actual query.

    Additional Resources:
    http://us.php.net/manual/en/function.mysql-real-escape-string.php http://us.php.net/manual/en/function.mysql-escape-string.php

提交回复
热议问题