問題描述
我收到此錯誤:
致命錯誤:在布爾值上調用成員函數 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()的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!