无法使用数据库类检索记录。

时间:2017-01-09 08:35:56

标签: php database

这是一个数据库类,它连接到数据库,包含主机名,用户名,密码和数据库名。 DatabaseConnect类之后的MembersModel类(也扩展了DatabaseConnect)应该检索信息。

<?php
class DatabaseConnect
{
    protected $conn;
    protected $host, $username, $password, $database;

    public function __construct($host, $username, $password, $database){
        // Create connection
        $this->conn = new mysqli($host, $username, $password,$database)
        OR die("There was a problem connecting to the database");

        return true;
    }

    public function query($sql) {
        $result = $this->conn->query($sql);
        if (!$result) {
            die('Invalid query:');
        }
        return $result;
    }

    public function __destruct(){
        $this->conn->close()
        OR die("Problem disconnecting from the database");
    }
}

class MemberModel extends DatabaseConnect 
{
    public function getAllMembers() {
        $result = $this->query("SELECT * FROM members");
        return $result;
    }
}

要从数据库连接和检索这是我一直在尝试做的事情

$db = new DatabaseConnect("localhost", "root", "", "pcaframework");
$allMembers = $db->getAllMembers();

while ($row = mysqli_fetch_assoc($allMembers)) {
    echo "First Name: " . $row['name'] ."<br />";
    echo "Last Name: "  . $row['email']  ."<br />";
    echo "<hr />";
}

但这就是我得到的&#34;致命错误:调用未定义的方法DatabaseConnect :: getAllMembers()&#34;。你能在这里指出问题吗?

1 个答案:

答案 0 :(得分:1)

您的$db对象应该是MemberModel的实例。 DatabaseConnect类不包含getAllMembers函数。

更改

$db = new DatabaseConnect("localhost", "root", "", "pcaframework");

$db = new MemberModel("localhost", "root", "", "pcaframework");