如果用户输入错误信息,则不显示错误消息

时间:2016-03-25 12:19:39

标签: php mysqli login

如果用户没有输入正确的登录组合,我试图在最后显示错误。但是,当我输入错误的密码或电子邮件时,错误消息不显示。任何建议

 <?php
 include ("connect.php");

if (isset($_POST["user_login"]) && (isset($_POST["user_pass"]))){
    // formatting field via reg replace to ensure email and password only conisists of letters and numbers preg_replace('#[^A-Za-z0-9]#i','', 
    $login_user = $_POST["user_login"];
    $login_password = $_POST["user_pass"];


    // password is encryted in DB (MD5) therefore user inputted password will not match encryted password in DB - we have to assign new var
    $decrypted_password = md5($login_password);

// Query which finds user (if valid) from DB - Achieving authentication via username and password       

$user_query = mysqli_query($connect, "SELECT * FROM users WHERE email = '$login_user' AND password = '$decrypted_password' AND closed = 'no' LIMIT 1"); 

    $check_user = mysqli_num_rows($user_query); // checking to see if there is infact a user which those credentials in the DB
        if ($check_user==1){

        while ($row = mysqli_fetch_array($user_query)){
                $id = $row['user_id'];
                $user_type = $row['account'];
            }
            $_SESSION["user_login"] = $login_user;
            // check the user type and redirect according to it
            if($user_type == "Student"){
             $student_page = "profile_student.php";
             header( "Location:{$student_page}" );

           } elseif ($user_type == "Landlord"){
              $landlord_page = "landlord_profile.php";
              header( "Location:{$landlord_page}" );

           } elseif ($user_type == "Administrator"){
               $admin_page = "admin_profile.php";
               header( "Location:{$admin_page}" );

           }else {
               $refresh_page = "sign_up.php";
               header( "Location:{$refresh_page}" ); // refresh page

            echo "You have entered an incorrect email or password. Please try again.";

           }
           }
}

    ?>

2 个答案:

答案 0 :(得分:1)

如果输入数据错误,您将重定向用户,并且仅在此之后您尝试回显消息,这不是如何工作的。阅读php_manual中的标题。可能这里最好的方法是在会话中存储错误消息,并在重定向检查后是否存在会话错误消息

else {
           $refresh_page = "sign_up.php";
            $_SESSION['error'] = "your error message"
           header( "Location:{$refresh_page}" ); // refresh page
       }

在sign_up.php文件中检查会话中是否存在错误消息

if(isset($_SESSION["error"])){
     echo $_SESSION["error"];
      unset($_SESSION["error"]);
  }

也许你应该纠正这个代码一点点)) 使用未设定的原因&#39;显示消息后,它应该从会话中删除,在其他情况下,如果您失败例如5次,它将显示5条消息))同时确保会话已启动session_start()希望它有所帮助:)

答案 1 :(得分:0)

只有当$user_type与您预期的任何类型都不匹配时,才会显示错误。

您需要在else数据块之后再次if ($check_user==1){来处理不存在具有该电子邮件或密码的用户的情况。