我如何使用PDO获取数据

时间:2018-05-06 14:13:13

标签: php pdo

我在数据库中有3个表..第一个用于登录信息的表,第二个用于书籍的表和第三个表具有user_id和book_id(外键)。 当特定用户输入他的名字和密码时,我会显示他所拥有的书。什么是我的代码中的错误..他只是实现isAuthenticated并且它工作..但他没有显示书籍为什么?

此功能用于登录

public function isAuthenticated()
{
    $query = "SELECT 1 FROM loginUser WHERE username = :username AND password = :password";
    $statment = $this->db->prepare($query);

    $statment->execute(
        array(
            ':username' => $this->username,
            ':password' => $this->Password
        ));
    $result = $statment->fetchColumn();

    $this->isAuthenticated= ($result == "1");
    return $this->isAuthenticated;
}

这个函数来获取这本书

public function getBooks()
{
    //SELECT loginUser.username, Library.nameOfBook FROM loginUser JOIN userBook JOIN Library ON userBook.user_id = loginUser.id AND userBook.book_id = Library.id WHERE loginUser.username="loay";
    $query = "SELECT Library.nameOfBook FROM loginUser JOIN userBook JOIN Library ON userBook.user_id = loginUser.id AND userBook.book_id = Library.id WHERE loginUser.username=':username'";
    $statment = $this->db->prepare($query);
    $statment->execute();
    $result = $statment->fetchAll();
    $this->isAuthenticated= ($result == "1");

    foreach($result as $row){
        echo $row['nameOfBook'] . "<br/>";
    }
    return $this->isAuthenticated;
}

在这里我从index.php

中的类创建对象
<?php
include_once('User.php');

if(isset($_POST['submit'])){

    $username = $_POST["user"];
    $password = $_POST["pass"];

    $object = new User();
    $object->username= $username;
    $object->Password=$password;

    if( $object->isAuthenticated() ){
        echo "User Verified";
        $object->getBooks();
    }
    else{
      echo "Wrong User Name Or Password";
    }
}
?>

1 个答案:

答案 0 :(得分:1)

您在getBooks()错误的查询中设置占位符:

loginUser.username=':username'

由于占位符周围有引号,因此它会搜索一个名为:username的用户。它应该是:

loginUser.username = :username

然后,您需要在执行查询时传递用户名(就像您登录时一样):

$statment->execute([
    ':username' => $this->username
]);

建议: 我会从该方法中删除this->isAuthenticated= ($result == "1"); - 行,因为它在该上下文中没有任何意义。书籍查询不应影响身份验证。或者更确切地说,如果没有经过身份验证的用户,您甚至无法进行该查询。