Second View
Second View

Reputation: 154

How i can fetch data using PDO

i has 3 table in database .. the first table for login info, second table for the books and third table has user_id and book_id (foreign key). when specific user enter his name and password i wand display what the book he has. whats the wrong in my code.. he just implement isAuthenticated and it work .. but he did not display the books why?

this function for login

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;
}

and this function to fetch the book

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;
}

and here i create object from class in 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";
    }
}
?>

Upvotes: 1

Views: 57

Answers (1)

M. Eriksson
M. Eriksson

Reputation: 13645

You're setting the placeholder in the query for getBooks() wrong:

loginUser.username=':username'

Since you have quotes around the placeholder, it will search for a user that's literally called :username. It should be:

loginUser.username = :username

Then you need to pass the username when you execute the query (like you do for the login):

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

Suggestion: I would remove the this->isAuthenticated= ($result == "1");-line from that method, since it doesn't make any sense in that context. The books query shouldn't affect the authentication. Or rather, you can't even do that query without an authenticated user.

Upvotes: 1

Related Questions