使用Mysqli进行面向对象的CRUD

时间:2016-01-14 17:10:01

标签: php oop mysqli

我正在尝试用PHP学习OOP编程。到目前为止,我有几个基本的东西,但我不知道如何将我的结果回显到页面。我编写了Database类和Category类我想回应read函数的结果,但我不知道该怎么做。有人可以帮我重构这个,所以我可以使用这两个类吗?

这是我的代码

class Database {
private $_connection;
private $_host = "localhost";
private $_username = "root";
private $_password = "";
private $_database = "cmsi";

// Conect to database is private and can only be used by getConection function result is returned object of mysqli class
//can be seen in var_dump() function
private function conect() {
    //$this refers to class Database and her functions and propertys are being acsessed via -> sign
    $this->_connection = new mysqli($this->_host, $this->_username,
                                    $this->_password, $this->_database);

    // Error handling
    if(mysqli_connect_error()) {
        trigger_error("Failed to conencto to MySQL: " . mysql_connect_error(),
                      E_USER_ERROR);
    }
    return $this->_connection;

}
//Safest way to iniate conection
public function getConection(){
    return $this -> conect();
}
}


 class Category{
private $db_sql;
public function  __construct($db){
    $this->db_sql = $db;
}

public function read(){
    $conection = $this->db_sql;
    $query = "Select * from category";
    $result = $conection -> query($query);
    return $result;
   }

 }

$db = new Database();
$conection = $db->getConection();
$obj = new Category($conection);
$obj->read();

1 个答案:

答案 0 :(得分:0)

你几乎就在那里。只需将结果集存储在变量中并循环遍历它,如下所示:

// your code

$db = new Database();
$conection = $db->getConection();
$obj = new Category($conection);

// store the result set
$result_set = $obj->read();

// loop through the result set
while($row = $result_set->fetch_array()){

    // your code

}