SQLite调用成员函数fetch()

时间:2017-12-01 20:47:31

标签: php sqlite

运行此代码时,我在readChatMessage方法中收到以下错误。我找不到错误。你是否认为这是因为我在其他地方读到了一个丢失的try和catch块?

Fatal error: Uncaught Error: Call to a member function fetch() on boolean in /opt/lampp/htdocs/A01/src/Mensa/Data.php:23 Stack trace: #0 /opt/lampp/htdocs/A01/src/Mensa/Data.php(16): Mensa\Data->readChatMessages() #1 /opt/lampp/htdocs/A01/src/Mensa/Application.php(19): Mensa\Data->__construct() #2 /opt/lampp/htdocs/A01/public/index.php(8): Mensa\Application->__construct() #3 {main} thrown in /opt/lampp/htdocs/A01/src/Mensa/Data.php on line 23

Data.php:

<?php
namespace Mensa;

require_once(__DIR__.'/Data/ChatMessage.php');
require_once(__DIR__.'/Data/MealSuggestion.php');
use Mensa\Data\ChatMessage;use Mensa\Data\MealSuggestion;use DateTime;use PDO;
class Data{
    const DATA_DIR = __DIR__.'/../../data';
    const DATABASE_FILE = self::DATA_DIR.'/mensa.sqlite';

    protected $chatMessages;
    protected $mealSuggestions;

    function __construct(){
        $this->db = new PDO('sqlite:'.self::DATABASE_FILE);
        $this->readChatMessages();
        $this->readMealSuggestions();
    }


    protected function readChatMessages(){
        $chatMessages = $this->db->query('SELECT*FROM chatmessage');
        while($chatMessageData=$chatMessages->fetch()){
            ...
        }
    }


    protected function readMealSuggestions(){
        $mealSuggestions =  $this->db->query('SELECT*FROM mealsuggestion');
        while($mealSugesstionData=$mealSuggestions->fetch()){
        ...
        }
    }

 protected $db;   
}
?>

1 个答案:

答案 0 :(得分:0)

这意味着失败了: $chatMessages = $this->db->query('SELECT*FROM chatmessage');

因此$chatMessages的值为false,因此下一行$chatMessageData=$chatMessages->fetch()会引发错误