在布尔值上调用成员函数 fetch()

Call to a member function fetch() on boolean(在布尔值上调用成员函数 fetch())
本文介绍了在布尔值上调用成员函数 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 'Poczenie nawizane!';
            }
            catch(PDOException $e) {
                echo 'Poczenie nie mogo 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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Why can#39;t I update data in an array with foreach loop?(为什么我不能用 foreach 循环更新数组中的数据?)
Foreach for arrays inside of an array(Foreach 用于数组内的数组)
PHP array get next key/value in foreach()(PHP 数组在 foreach() 中获取下一个键/值)
Using preg_match on a multidimensional array to return key values arrays(在多维数组上使用 preg_match 返回键值数组)
php foreach as key, every two number as a group(php foreach 为key,每两个数字为一组)
Treat a PHP class that implements Iterator as an array(将实现 Iterator 的 PHP 类视为数组)