DB为空,但PDO执行返回bool(True)

时间:2018-05-12 20:50:51

标签: php pdo

我想为学生和老师登录学校系统。

    $query = $pdo->prepare("SELECT `username`, `password` FROM `teachers` WHERE `username` = :username");
    $result = $query->execute(array(
    ":username" => $username));

    if($result) {
       $_SESSION["username"]["who"] = array($username, "teacher");
       echo("<script>location.href = 'home.php';</script>");
    } else {
       $query = $pdo->prepare("SELECT `username`, `password` FROM `students` WHERE `username` = :username");
       $result = $query->execute(array(
       ":username" => $username));

       if($result) {
          $_SESSION["username"]["who"] = array($username, "student");
          echo("<script>location.href = 'home.php';</script>");
       } else {
          echo("<script>alert('Error.'); location.href = 'index.php';</script>");
       }
    }

我的学生数据库中只有一个用户名。 但是,如果我可以尝试使用随机用户名登录,我每次都获得$ result = True。 当教师的桌子是空的时,为什么$结果是真的?

1 个答案:

答案 0 :(得分:4)

执行结果是不受约束的陈述。

我建议使用fetchObject

try {
  $statement = $pdo->prepare("SELECT 1 as `exists` FROM `teachers` WHERE `username` = :username LIMIT 1");
  $statement->execute([":username" => $username]);

  $teacher = $statement->fetchObject();

  if ($teacher) {
    // success here
    $_SESSION['user'] = ['username' => $username, 'role' => 'teacher'];

    session_write_close(); // gracefully closing session
    header('Location: /home.php');
    exit(0);
  }
  throw new Exception('User not found');
}
catch (Exception $exception) {
  header('Location: index.php');
  exit(-1);
}