【问题标题】:Extending the database class to get result from MySql扩展数据库类以从 MySql 获取结果
【发布时间】:2016-12-11 07:51:06
【问题描述】:

我一直在尝试学习如何在 MVC 结构中使用 php 类进行数据库操作。这是一个连接数据库的简单数据库类。

<?php
class Database
{
private $connect;
private $host, $username, $password, $databaseName;

public function __construct($host, $username, $password, $databaseName)
{
    $this->host = $host;
    $this->username = $username;
    $this->password = $password;
    $this->databaseName = $databaseName;

    $this->connect = new mysqli($this->host, $this->username, $this->password, $this->databaseName);

    if ($this->connect->connect_error) {
        die('Connect Error (' . $this->connect->connect_errno . ') '. $this->connect->connect_error);
    }

    return true;
}

public function __destruct()
{
    $this->connect->close();
}
}

实例化连接类

$db = new Database("localhost", "root", "", "framework");

到这里就好了,如果有错误,它会连接并显示和错误。

现在我在数据库中有一个表'Members',其中包含三列 1. Id、2. Name 和 3. Email 并在 members 表中显示记录 我在模型文件夹(MVC)中有一个成员模型文件。我试图像这样扩展数据库类

class Members extends Database {
    public function getMembers() {
        $result = $this->connect->query("SELECT * FROM members");
        return $query->row;
    }
}

我无法(过去 24 小时)做的是显示结果。

附:即使你能建议我一个关于如何扩展数据库类的教程也会很棒。

【问题讨论】:

  • $query 中的Members 是什么?
  • @RC.,成员表中有记录,我正在尝试显示所有记录。

标签: php mysql database class oop


【解决方案1】:

1)。子类不能直接访问其父 private 属性,因此您需要 public 修饰符方法从其任何子类访问其属性

public function getConnect(){
return $this->connect;
}
public function getUsername(){
return $this->username;
}

public function getPassword(){
return $this->password;
}

public function getDatabaseName(){
return $this->databaseName;
}

2).Parent 有一个构造函数来初始化这些$host$username, $password$databaseName,因此子构造函数必须在自己的构造函数中引用其父构造函数构造函数

继承中,我们不直接实例化父类,而是通过扩展它的类来初始化它的父属性(所以$host$username$password、@987654328 @通过子类初始化)。如果还是直接实例化父类,那么使用继承就没有意义了。

class Members extends Database {

  public __construct( $host, $username, $password, $databaseName){
    parent::__construct( $host, $username, $password, $databaseName);
   }
    public function getMembers() {

        $result = $this->getConnect()->query("SELECT * FROM members");
        return $query->row;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-09
    • 1970-01-01
    • 2020-09-30
    • 2015-03-11
    • 1970-01-01
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    相关资源
    最近更新 更多