Call to a member function fetch() on boolean(在布尔值上调用成员函数 fetch())
问题描述
我收到此错误:
致命错误:在布尔值上调用成员函数 fetch()C:xampphtdocs epogeneratormodeldatabase.php 第 34 行
Fatal error: Call to a member function fetch() on boolean in C:xampphtdocs epogeneratormodeldatabase.php on line 34
当我运行此代码时:
class database
{
private $user = 'root';
private $pass = '';
public $pdo;
public function connect() {
try {
$this->pdo = new PDO('mysql:host=localhost; dbname=generatordatabase', $this->user, $this->pass);
echo 'Połączenie nawiązane!';
}
catch(PDOException $e) {
echo 'Połączenie nie mogło zostać utworzone: ' . $e->getMessage();
}
}
public function createTable() {
$q = $this->pdo -> query('SELECT * FROM article');
while($row = $q->fetch()) {
echo $row['id'].' ';
}
$q->closeCursor();
}
}
?>
推荐答案
根据 PHP 手册 PDO::查询
PDO::query() 返回一个 PDOStatement 对象,或者失败时返回 FALSE.
PDO::query() returns a PDOStatement object, or FALSE on failure.
看起来您的查询失败(在第 33 行)并因此返回 BOOLEAN (false),可能是因为在执行时,PDO 尚未连接到包含名为 article的表的数据库强>.在 connect() 方法中,我看到它尝试连接到名为generatordatabase"的数据库;确保在调用 createTable() 之前建立此连接,否则确保它包含一个名为article"的表.
It looks like your query is failing (on line 33) and thus returning a BOOLEAN (false), likely because at that point in execution, PDO has not connected to a database that contains a table called article. In the connect() method I see that it tries to connect to a db called 'generatordatabase'; ensure this connection is being made prior to calling createTable(), otherwise ensure that it contains a table called 'article'.
我建议添加更多代码示例,例如在触发错误之前调用此类/方法的代码.
I would recommend adding some more code examples, for instance the code that calls this class/method before the error is triggered.
这篇关于在布尔值上调用成员函数 fetch()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在布尔值上调用成员函数 fetch()


基础教程推荐
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 使用 PDO 转义列名 2021-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01