0

Why does the last else statement in my PHP code is not working? When I entered non-existing accounts, it is not displaying the "Incorrect email or password" error message.

<?php

include("connection.php");

$email_id = $password = $emailErr = $passErr = $loginErr = "";

if(isset($_POST["butLogin"])){
    if(empty($_POST["email_id"])){
        $emailErr = "This field cannot be empty!";
    }else{
        $email_id = $_POST["email_id"];
    }

    if(empty($_POST["password"])){
        $passErr = "This field cannot be empty!";
    }else{
        $password = $_POST["password"];
    }

    if($email_id && $password){
        $check_record = mysqli_query($connection, "SELECT * FROM user WHERE password = '$password' AND email = '$email_id'");

        if (mysqli_num_rows($check_record) > 0 ){
            $row = mysqli_fetch_assoc($check_record);
            if(($email_id == $row['email']) && ($password == $row['password'])){
                if($row['user_type'] == 1){
                    header("Location: /php/admin/index");
                }else{
                    header("Location: /php/user/index");
                }
            }else{
                $loginErr = "Incorrect email or password.";
            }   
        }
    }
}
?>
u_mulder
  • 54,101
  • 5
  • 48
  • 64
Nico Loco
  • 5
  • 2

2 Answers2

0

If account doesn't exist, mysqli_num_rows will return 0. You should move the else condition in that block.

    if (mysqli_num_rows($check_record) > 0 ){
        $row = mysqli_fetch_assoc($check_record);
        if(($email_id == $row['email']) && ($password == $row['password'])){
            if($row['user_type'] == 1){
                header("Location: /php/admin/index");
            }else{
                header("Location: /php/user/index");
            }
        }   
    } else{
        $loginErr = "Incorrect email or password.";
    }
dvillar
  • 16
  • 2
  • Thank you! but now it's displaying "incorrect email or password" that supposed to be displayed **after** I enter something. P.S. I get it now, but why does the last else is triggering? – Nico Loco Jun 19 '18 at 16:38
0

The else statement will never get touched because it is checked on the wrong conditional. If the query returns 0, that is because there is no email/password combination found, but you do not handle this case.

Move your else statement to look like the following:

if($email_id && $password){
    $check_record = mysqli_query($connection, "SELECT * FROM user WHERE password = '$password' AND email = '$email_id'");

    if (mysqli_num_rows($check_record) > 0 ){

       "QUERY PROCESSING HERE"

    }else{
            $loginErr = "Incorrect email or password.";
    }
}
Greg Gardner
  • 190
  • 11
  • Thank you! but now it's displaying "incorrect email or password" that supposed to be displayed after I enter something. P.S. I get it now, but why does the last else is triggering? – Nico Loco Jun 19 '18 at 16:45