【问题标题】:PHP file to check if email exists in database [duplicate]PHP文件检查数据库中是否存在电子邮件[重复]
【发布时间】:2019-10-02 04:51:54
【问题描述】:

我正在尝试检查我的数据库中是否已经存在电子邮件,我认为我有正确的代码可以检查,但由于某种原因,我仍然可以使用相同的电子邮件创建另一个用户。我想同时检查用户名和电子邮件。

这是我目前拥有的代码:

<?php
  if (empty($username) || empty($email) || empty($pwd) || empty($pwdcheck)){
    header("Location: ../cadastrar.php?error=emptyfields&nome=".$username."&email=".$email);
    exit();
  }else if(!filter_var($email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9]*$/", $username)){
    header("Location: ../cadastrar.php?error=invalidmailusername");
    exit();
  }else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
    header("Location: ../cadastrar.php?error=invalidmail&nome=".$username);
    exit();
  }else if(!preg_match("/^[a-zA-Z0-9]*$/", $username)){
    header("Location: ../cadastrar.php?error=invalidusername&email=".$email);
    exit();
  }else if($pwd !== $pwdcheck){
    header("Location: ../cadastrar.php?error=passwordcheck&email=".$email."&nome=".$username);
    exit();
  }else{
    $sql = "SELECT usuario FROM users WHERE usuario=?";
    $stmt = mysqli_stmt_init($conn);
    if (!mysqli_stmt_prepare($stmt, $sql)){
      header("Location: ../cadastrar.php?error=sqlerror");
      exit();
    }else{
      mysqli_stmt_bind_param($stmt, "s", $username);
      mysqli_stmt_execute($stmt);
      mysqli_stmt_store_result($stmt);
      $resultCheck = mysqli_stmt_num_rows($stmt);
      if ($resultCheck > 0){
        header("Location: ../cadastrar.php?error=usertaken&email=".$email);
        exit();
      }else{
        $sql = "INSERT INTO users (nomecompleto ,usuario, emailuser, pwdusers) VALUES (?, ?, ?, ?)";
        $stmt = mysqli_stmt_init($conn);
        if (!mysqli_stmt_prepare($stmt, $sql)){
          header("Location: ../cadastrar.php?error=sqlerror");
          exit();
        }else{
          $hashedpwd = password_hash($pwd, PASSWORD_DEFAULT);

          mysqli_stmt_bind_param($stmt, "ssss", $nomecompleto, $username, $email , $hashedpwd);
          mysqli_stmt_execute($stmt);
          header("Location: ../cadastrar.php?cadastro=sucesso");
          exit();
        }
      }
    }
  }
  mysqli_stmt_close($stmt);
  mysqli_close($conn);
}else{
  header("Location: ../cadastrar.php");
  exit();
}

【问题讨论】:

    标签: php html database mysqli


    【解决方案1】:

    您应该将$sql = "SELECT usuario FROM users WHERE usuario=?"; 中的usuario=? 替换为emailuser=?,并将绑定值替换为$email。您当前不是在检查电子邮件,而是在检查姓名。

    【讨论】:

    • 我想检查两者
    • 使用"SELECT usuario, emailuser FROM users WHERE usuario=? AND emailuser=?" 和绑定mysqli_stmt_bind_param($stmt, "ss", $username, $email);。这样您就可以检查是否使用了这两个项目。请注意,您仍然可以使用不同的用户名使用相同的电子邮件(John 和 Paul 可以注册相同的电子邮件,因为用户不匹配)。要单独检查值并避免这种情况,请将查询中的 AND 替换为 OR
    • 成功了,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    • 2021-04-24
    • 2017-07-26
    • 2017-08-12
    • 2012-03-13
    • 2019-09-17
    • 2013-06-08
    相关资源
    最近更新 更多