4

I know there are few other questions on here with this title, but they seem to be case specific or I just can't wrap my head around it but I'm getting that error on this code, and I can't figure out why.

$db = new PDO($dsn, $username, $password);
$query = "Select * FROM book INNER JOIN course
          ON book.course = course.courseID
          ORDER BY courseTitle";

//query result
$books = array();
$sth = $db->query($query);
while( $row = $db->fetch(PDO::FETCH_ASSOC) ) {
    $books[] = $row; // appends each row to the array
}

I thought maybe my query was wrong, so I tried an example from a PDO tutorial, and I got the same type of error. Is there something I have to declare or am I leaving something out?

5
  • 2
    fetch on $sth, not on $db.
    – deceze
    Commented May 1, 2013 at 5:47
  • I changed to $sth, now I get "Call to a member function fetch() on a non-object" error
    – john
    Commented May 1, 2013 at 5:52
  • 1
  • Then query returned false because your query was bad. Use var_dump($db->errorInfo()) to figure out what's wrong.
    – deceze
    Commented May 1, 2013 at 5:54
  • my query is incorrect, I will work on the syntax. thank you.
    – john
    Commented May 1, 2013 at 5:58

1 Answer 1

13

You should use $sth instead of $db when using PDO-functions relevant to query on the resultset from the query.

$db = new PDO($dsn, $username, $password);
$query = "Select * FROM book INNER JOIN course
ON book.course = course.courseID
ORDER BY courseTitle";

//query result
$books = array();
$sth = $db->query($query);
while( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
  $books[] = $row; // appends each row to the array
}

When debugging PDO. Add this line after creation of PDO-object:

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Then exceptions will be thrown when there are errors in the query/queries.

8
  • 1
    Well, $db is also a PDO object on which you can use "PDO functions"...
    – deceze
    Commented May 1, 2013 at 5:51
  • hey best, thank you for responding, I made the change you supplied, and now I get this error. 'Call to a member function fetch() on a non-object' is book not a member object?
    – john
    Commented May 1, 2013 at 5:52
  • @deceze - ah I know, I explained it rather poorely. Maybe it's more clear now? Commented May 1, 2013 at 5:53
  • @john - my guess is that you've never used PDO before on the computer you're developing? Is PDO active? Check it with phpinfo(). Commented May 1, 2013 at 5:54
  • 2
    @bestprogrammerintheworld: if PDO weren't active, it would crash on new PDO(...). I'm betting on a syntax error in the query itself.
    – user1233508
    Commented May 1, 2013 at 5:55

Not the answer you're looking for? Browse other questions tagged or ask your own question.