Check record exists db - error show

后端 未结 3 1816
[愿得一人]
[愿得一人] 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:26

    It would be easier if you just did a quick true/false check in the SQL and checked the flag that came back.

    $sql = "SELECT "
      . "(SELECT 1 FROM `users` WHERE `username` = '" . mysql_real_escape_string($username) . "'), "
      . "(SELECT 1 FROM `users` WHERE `email` = '" . mysql_real_escape_string($email) . "')";
    
    $query = mysql_query($sql);
    
    if (mysql_num_rows($query) > 0) {
      $foundFlags = mysql_fetch_assoc($query);
      if ($foundFlags['username']) {
        $error[] = "username is existing";
      }
    
      if ($foundFlags['email']) {
        $error[] = "email is existing";
      }
    } else {
      // General error as the query should always return
    }
    

    When it does not find an entry, it will return NULL in the flag, which evaluates to false, so the if condition is fine.

    Note that you could generalise it for a field list like this:

    $fieldMatch = array('username' => $username, 'email' => $email);
    
    $sqlParts = array();
    foreach ($fieldMatch as $cFieldName => $cFieldValue) {
      $sqlParts[] = "(SELECT 1 FROM `users` WHERE `" . $cFieldName . "` = '" . mysql_real_escape_string($cFieldValue) . "')";
    }
    
    
    $sql = "SELECT " . implode(", ", $sqlParts);
    
    $query = mysql_query($sql);
    
    if (mysql_num_rows($query) > 0) {
      $foundFlags = mysql_fetch_assoc($query);
      foreach ($foundFlags as $cFieldName => $cFlag) {
        if ($foundFlags[$cFieldName]) {
          $error[] = $cFieldName . " is existing";
        }
      }
    } else {
      // General error as the query should always return
    }
    

    NB. Note that assumes all fields are strings, or other string-escaped types (eg. date/time).

提交回复
热议问题