Php mysQli脚本与AND运算符不按预期工作

时间:2017-02-16 22:47:36

标签: php mysqli

我一直在编写看似永远不会按照我希望的方式工作的查询。在此脚本中,如果尝试登录的用户user_level 'Admin',则应该直接adminhome.php如果用户user_level 'Employee',则应将其定向到employeehome.php。我已经使用user_level Admin创建了这两个用户Amanda,使用user_level 'Employee'创建了Hugo来测试脚本,但无论我是谁登录,它都会触发$error

的login.php

<?php 
 if($_SERVER["REQUEST_METHOD"] == "POST") {

    $myusername = mysqli_real_escape_string($db,$_POST['username']);
    $mypassword = $_POST['password'];          


    $hashedPasswordQry = "SELECT password FROM users WHERE username = '$myusername'";

   $userLevel = mysqli_query($db, "SELECT user_level FROM users WHERE username='".$myusername."'");

    $result = mysqli_query($db,$hashedPasswordQry);
    $row = mysqli_fetch_array($result,MYSQLI_ASSOC);

    $count = mysqli_num_rows($result);

    // If result matched $myusername and $mypassword, table row must be 1 row
    if($count == 1 && (password_verify($mypassword, $row['password'])) && $userLevel  == 'Admin') {

        $_SESSION['login_user'] = $myusername;


        header("location: user/adminhome.php");

    }elseif($count == 1 && (password_verify($mypassword, $row['password'])) && $userLevel == 'Employee'){

           $_SESSION['login_user'] = $myusername;


        header("location: user/employeehome.php");
    }
else{
     $error = '<h5 style="text-align: center;" class="alert alert-danger" >Your username  or password is invalid</h5>';

}
}
?>

1 个答案:

答案 0 :(得分:0)

你只使用两个非常相似的选择。您可以通过用逗号SELECT this_column, that_column FROM ...分隔查询中的多个列。在执行两个查询时,您只访问密码查询的结果而不是$userLevel结果。更正确的版本如下:

$query = "SELECT password, user_level FROM users WHERE username = '$myusername'";

$result = mysqli_query($db, $query);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);

$count = mysqli_num_rows($result);

if($count == 1 && (password_verify($mypassword, $row['password'])) && $row['user_level']  == 'Admin')
{
    // do stuff
} elseif ($count == 1 && (password_verify($mypassword, $row['password'])) && $row['user_level'] == 'Employee')
{
    // do stuff
}