检查用户名是否存在,还要检查密码是否匹配

时间:2017-06-12 19:30:32

标签: php mysql

您好我在学习如何使用预备语句。我已经弄清楚如何检查密码和电子邮件地址匹配但是我希望在参数检查中还有一个条件,检查电子邮件地址是否在系统中,并检查密码是否不匹配。

如何添加' IF / ELSE'检查电子邮件地址的参数,然后检查密码是否匹配(目前它是否匹配)。

任何帮助将不胜感激:

$emailAddress = $_POST['emailAddress'];
$password = $_POST['password'];

if ($stmt = $conn->prepare("SELECT `password` FROM `users` WHERE emailAddress=?")) {

    $stmt->bind_param("s", $emailAddress);
    $stmt->execute();

    $stmt->bind_result($result);
    $stmt->fetch();
    $stmt->close();
}


if(password_verify($password, $result)){
    // Login if the email and password matches
    session_start();
    $_SESSION['loggedin'] = true;
    $_SESSION['emailAddress'] = $emailAddress;
    header('Location: ../index.php');
}
else{

    header('Location: ../login.php?error=1');
}

$conn->close();

1 个答案:

答案 0 :(得分:2)

将代码修改为:

$emailAddress = $_POST['emailAddress'];
$password = $_POST['password'];

if ($stmt = $conn->prepare("SELECT `password` FROM `users` WHERE emailAddress=?")) {

    $stmt->bind_param("s", $emailAddress);
    $stmt->execute();

    $stmt->bind_result($result);
    $stmt->fetch();

    /** 
     * Another option can be 
     * if ($stmt->fetch()) { 
     */

    if (!empty($result)) {
        // something is found
        if (password_verify($password, $result)){
            // Login if the email and password matches
            session_start();
            $_SESSION['loggedin'] = true;
            $_SESSION['emailAddress'] = $emailAddress;
            header('Location: ../index.php');    // or whatever
            exit;
        } else {
            // No password match
            header('Location: ../login.php?error=1');    // or whatever
            exit;
        }
    } else {
        // No email found
        header('Location: ../login.php?error=2');    // or whatever
        exit;
    }
    $stmt->close();
}