-1

Hi There Im learning how to use prepared statements. I have figured out how to check of the password and email address match however I wish to have a criteria in the argument check also that the email address is in the system and also the check if the password does not match.

How do I add in 'IF/ELSE' argument to check the email address, then check if the password matches (which it currently does this).

Any help would be appreciated:

$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();
danjbh
  • 615
  • 10
  • 21

1 Answers1

2

Modify you code as:

$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();
}
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
u_mulder
  • 54,101
  • 5
  • 48
  • 64