Php 获得;null上的查询();尝试使用PDO OOP类回显数据库时出错?

Php 获得;null上的查询();尝试使用PDO OOP类回显数据库时出错?,php,pdo,Php,Pdo,我在这段代码中遇到了另一个错误。它是: 成功连接 致命错误:未捕获错误:在index5.php:29堆栈跟踪:#0 index5.php(44):User->getAllUsers()#1 index5.php(55):ViewUser->showalUsers()#2{main}在第29行的index5.php中抛出 我试图从名为“indeximg”的数据库表中回显数据,但这段代码给出了上面的错误。我不知道如何解决这个问题。这是我的代码: 从null调用query()方法,因为您没有从con

我在这段代码中遇到了另一个错误。它是:

成功连接 致命错误:未捕获错误:在index5.php:29堆栈跟踪:#0 index5.php(44):User->getAllUsers()#1 index5.php(55):ViewUser->showalUsers()#2{main}在第29行的index5.php中抛出

我试图从名为“indeximg”的数据库表中回显数据,但这段代码给出了上面的错误。我不知道如何解决这个问题。这是我的代码:

从null调用query()方法,因为您没有从connect()函数返回任何内容。添加一行,如注释中所示

protected function connect() {  

try {
    $this->conn = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->db_name, $this->username, $this->password);
    $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully"; 
    return $this->conn;//Add this line
} catch(PDOException $e) {
    echo 'Connection Error: ' . $e->getMessage();
}

$this->conn = null;
}

connect()
函数中有几个问题:

首先,即使连接成功,也要将
$this->conn
设置为null

其次,将函数链接到不返回任何内容的
connect()
函数的结果:

protected function connect() 
{   
    try {
        $this->conn = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->db_name, $this->username, $this->password);
        $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        echo "Connected successfully";
    } catch(PDOException $e) {
        die('Connection Error: ' . $e->getMessage()); // Or do something else to handle the error
    }

    return $this->conn; 
}

您的connect()方法不返回连接。。。因此,您不能像以前那样链接该方法。我认为用户不应该扩展数据库,如果您想了解更多,请查看未来的组合。^^^正如@zebnat提到的,
User
不是
数据库的特殊类型。作为一个偶尔使用东西的人,我觉得这很没人性。你可能也会发现这很有用:可能是@Lars Stegelitz的复制品是的,这正是问题所在。我现在修好了,谢谢这修好了!非常感谢你,我昨天一整天都在努力解决这个问题。谢谢,谢谢!!是的,这是修复,谢谢!我有一种感觉,这是一个零连接线。非常感谢你的建议!!