1.在学习php时用pdo模式连接数据库,查询数据时,在调用fetch方法时出现错误:fatal error: call to a member function fetch() on a non-object
2.代码
//pdo连接数据库方式 try{ $db_conn = new pdo('mysql:host = localhost;dbname = test','root','123456'); echo 连接成功!; } catch(pdoexception $e){ echo could not connect to datebase; }//从表中选取数据 $stmt = $db_conn->query('select * from user'); var_dump($stmt);//显示结果 while ($row = $stmt->fetch()) { echo $row['name'].$row['number'].$row['class']; }
3.错误结果
4.数据库
回复内容: 1.在学习php时用pdo模式连接数据库,查询数据时,在调用fetch方法时出现错误:fatal error: call to a member function fetch() on a non-object
2.代码
//pdo连接数据库方式 try{ $db_conn = new pdo('mysql:host = localhost;dbname = test','root','123456'); echo 连接成功!; } catch(pdoexception $e){ echo could not connect to datebase; }//从表中选取数据 $stmt = $db_conn->query('select * from user'); var_dump($stmt);//显示结果 while ($row = $stmt->fetch()) { echo $row['name'].$row['number'].$row['class']; }
3.错误结果
4.数据库
你的sql查询出错了,$stmt都是false了,还怎么执行fetch呀
foreach ($db_conn->query('select * from user') as $row) { print $row['name'] . \t; print $row['age'] . \t; }
参考手册。问题一般都可以解决。:)
query执行sql后可以直接用fetchall获取结果集,这样就不需要while循环逐条fetch了:
query($sql)->fetchall(pdo::fetch_assoc) );
可以在phpmyadmin中把你要查询的sql语句运行一下,
select * from user,可能它就是错的。
我一直是这样查错的,希望能帮到你。
