php 调用未定义的方法 PDO::fetch()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16313353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call to undefined method PDO::fetch()
提问by john
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?
我想我的查询可能是错误的,所以我尝试了PDO
教程中的一个示例,但出现了相同类型的错误。有什么我必须申报的还是我遗漏了什么?
回答by bestprogrammerintheworld
You should use $sth instead of $db when using PDO-functions relevant to query on the resultset from the query.
当使用与查询结果集相关的 PDO 函数时,您应该使用 $sth 而不是 $db。
$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:
调试 PDO 时。在创建 PDO 对象后添加这一行:
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Then exceptions will be thrown when there are errors in the query/queries.
然后当查询/查询中有错误时将抛出异常。