【问题标题】:DB object not working (PHP): "Call to a member function query() on a non-object"DB 对象不工作(PHP):“在非对象上调用成员函数 query()”
【发布时间】:2014-01-15 14:47:34
【问题描述】:

我正在做一点 PHP 并尝试查询数据库,然后对返回的 rows 对象做一些事情。我的页面一直说:“在非对象上调用成员函数 query()”

这是 PHP:

public function __contruct() {
    $this->db = new PDO("mysql:dbname=DBName;host=mysql.our.host", 'User_Admin_Name', 'Password');
    $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

public function getEvents() {
    $sql = 'SELECT this FROM that';
    $rows = $this->db->query($sql); //This is the line that the error indicates is problematic
}

有谁知道为什么它不能将 db 识别为常规的 db 对象?

【问题讨论】:

    标签: php mysql database object


    【解决方案1】:

    这一行:

    public function __contruct() {
                         ^
    

    construct 这个词拼错了(construct),除非是拼写错误。

    立即尝试:

    public function __construct() {
    

    public function __construct() {
        $this->db = new PDO("mysql:dbname=DBName;host=mysql.our.host", 'User_Admin_Name', 'Password');
        $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    
    public function getEvents() {
        $sql = 'SELECT this FROM that';
        $rows = $this->db->query($sql); //This is the line that the error indicates is problematic
    }
    

    【讨论】:

    • 我自己也犯过几次这样的错误。我盯着它看了整整一分钟,直到它击中我。 @CaptainStack
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多