3

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?

Subedi Kishor
  • 5,906
  • 5
  • 35
  • 53
john
  • 775
  • 3
  • 15
  • 31
  • 2
    `fetch` on `$sth`, not on `$db`. – deceze May 01 '13 at 05:47
  • I changed to $sth, now I get "Call to a member function fetch() on a non-object" error – john May 01 '13 at 05:52
  • 1
    [PDO query fails but I can't see any errors. How to get an error message from PDO?](http://stackoverflow.com/questions/15990857/reference-frequently-asked-questions-about-pdo#15990858) – DCoder May 01 '13 at 05:54
  • Then `query` returned `false` because your query was bad. Use `var_dump($db->errorInfo())` to figure out what's wrong. – deceze May 01 '13 at 05:54
  • my query is incorrect, I will work on the syntax. thank you. – john May 01 '13 at 05:58

1 Answers1

12

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.

bestprogrammerintheworld
  • 5,417
  • 7
  • 43
  • 72