PDO在null上调用成员函数prepare()

时间:2016-04-21 18:48:30

标签: php mysql pdo

我正在开发一个使用MySQL数据库的项目,我已经制作了这段代码,并且在我一个月前停止在项目中工作之前它已经运行了。所以,我收到错误:Call to a member function prepare() on null in。我知道已经有很多问题已经存在,但我似乎无法找到答案。

我的数据库类:

<?php
class Database {

    private $con;

    private $host;
    private $user;
    private $pass;
    private $data;

    public function __construct($host, $user, $pass, $data) {
        $this->host = $host;
        $this->user = $user;
        $this->pass = $pass;
        $this->data = $data;
    }

    public function connect() {
        try {
            $this->con = new PDO('mysql:host='.$this->host.';dbname='.$this->data.';charset=utf8', $this->user, $this->pass);
            $this->con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
            $this->con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
            return true;
        } catch (Exception $e) {
            return false;
        }
    }

    public function getRecentPosts($forum_id, $limit) {
        $stmt = $this->con->prepare("SELECT * FROM forums_topics INNER JOIN forums_posts ON forums_topics.tid = forums_posts.topic_id INNER JOIN core_members ON forums_posts.author_id = core_members.member_id WHERE forums_topics.forum_id =$forum_id AND forums_posts.new_topic =1 ORDER BY forums_topics.start_date DESC LIMIT $limit");
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}
?>

连接并包括:

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);

    require_once 'constants.php';
    require_once 'classes/database.class.php'; 

    $db = new Database($sql_host, $sql_user, $sql_pass, $sql_data);
    $db->connect();
?>

所以,由于某种原因,我的SELECT语句出了问题,但我似乎无法找到我做错的事。

提前致谢!

0 个答案:

没有答案