Call to undefined method PDO::fetch()
mysql, php
Solution
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.
Problem
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?