这是一个数据库类,它连接到数据库,包含主机名,用户名,密码和数据库名。 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;。你能在这里指出问题吗?
答案 0 :(得分:1)
您的$db
对象应该是MemberModel
的实例。 DatabaseConnect
类不包含getAllMembers
函数。
更改
$db = new DatabaseConnect("localhost", "root", "", "pcaframework");
要
$db = new MemberModel("localhost", "root", "", "pcaframework");