使用mysqli_fetch_assoc()函数进行用户身份验证

时间:2018-04-13 10:47:26

标签: php mysql

我一直试图使用mysqli_fetch_assoc函数验证用户输入,虽然它可以工作,即当用户名和密码正确时将用户重定向到主页,但它没有显示错误消息(s )当输入不正确时,如果用户名不正确,它会显示用户名错误消息。请问我该如何解决?这是代码

$username  = $password =  "";
$username_err = $password_err  = "";
//testing input values
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    //processing username input
    if (empty($_POST['username'])) {
        $username_err = " *username is required!";      
    }else{                              //if field is not empty
        $username = test_input($_POST['username']);
    }

    //processing password input
    if (empty($_POST['password'])) {
        $password_err = " *password is required!";
    }elseif (strlen($_POST['password']) < 8) {
        $password_err = " *password must not be less than 8 characters!";
    }else{                          //if field is not empty
        $password = md5($_POST['password']);
    }

    //comparing user input with stored details
    $sql = "SELECT * FROM users_log WHERE Username = '$username' AND Password = '$password'";
    $result = mysqli_query($dbconn, $sql);
    $row = mysqli_fetch_assoc($result);

    if ($row) {
        if ($row['Username'] != $username ) {
            $username_err = "Incorrect Username";
        }elseif ($row['Password'] != $password ) {
            $password_err = "Incorrect Password";
        }else{
            header("location:../home/homeIndex.php");
        }
    }

}

function test_input($input){
    $input = trim($input);
    $input = stripslashes($input);
    $input = htmlspecialchars($input);
    return $input;
}

html输出

<span><?php echo "$username_err<br>"; ?></span>
        <input type="text" name="username"  class="form-control" placeholder="Username" size="30">
        </div><br>


            <?php echo "$password_err<br>"; ?></span>
        <input type="password" name="password"  class="form-control" placeholder="Password" size="30" >
        </div><br>

3 个答案:

答案 0 :(得分:1)

if ($row) {
        if ($row['Username'] != $username ) {
            $username_err = "Incorrect Username";
        }elseif ($row['Password'] != $password ) {
            $password_err = "Incorrect Password";
        }else{
            header("location:../home/homeIndex.php");
        }
    }
当条件为真时,

$ row中的数据将执行。因此,如果条件如此,请使用

if ($row) {

            header("location:../home/homeIndex.php");

}else{

               $username_err = "Incorrect Username Or Password";

}

希望这能解决您的问题

答案 1 :(得分:0)

你在if($row)内包装了不正确的用户名条件,这不能用作内部查询,你正在检查用户名和密码,但是如果这些都是错误的,查询将返回0结果,这意味着if($row)是负面的,其中的任何内容都无效......请尝试以下内容:

if ($row) {
        header("location:../home/homeIndex.php");
} else {
        $error = "Incorrect Username or password";

}

为什么会这样和$error = "incorrect username or password,这是因为如果用户名不正确或密码不正确,您实际上并没有单独检查用户名和密码。你正在检查它们,这使得if($row)不能按你的意愿工作,所以你最好先尝试一下。

答案 2 :(得分:0)

如果用户名或密码不正确,$ result必须为空。检查是否为空($ result)。