Class xử lý database trong hướng đối tượng (phần 1)(ok)

https://freetuts.net/class-xu-ly-database-trong-huong-doi-tuong-phan-1-188.html

C:\xampp\htdocs\php\DB_driver.php

<?php
class DB_driver {
  private $__conn;
  public function connect() {
    if (!$this->__conn) {
      $this->__conn = mysqli_connect('localhost', 'root', '', 'demo') or die('Lỗi kết nối');
      mysqli_query($this->__conn, "SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'");
    }
  }
  public function dis_connect() {
    if ($this->__conn) {
      mysqli_close($this->__conn);
    }
  }
  public function insert($table, $data) {
    $this->connect();
    $field_list = '';
    $value_list = '';
    foreach ($data as $key => $value) {
      $field_list .= ",$key";
      $value_list .= ",'" . mysqli_escape_string($this->__conn, $value) . "'";
    }
    $sql = 'INSERT INTO ' . $table . '(' . trim($field_list, ',') . ') VALUES (' . trim($value_list, ',') . ')';
    return mysqli_query($this->__conn, $sql);
  }
  public function update($table, $data, $where) {
    $this->connect();
    $sql = '';
    foreach ($data as $key => $value) {
      $sql .= "$key = '" . mysqli_escape_string($this->__conn,$value) . "',";
    }
    $sql = 'UPDATE ' . $table . ' SET ' . trim($sql, ',') . ' WHERE ' . $where;
    return mysqli_query($this->__conn, $sql);
  }
  public function remove($table, $where) {
    $this->connect();
    $sql = "DELETE FROM $table WHERE $where";
    return mysqli_query($this->__conn, $sql);
  }
  public function get_list($sql) {
    $this->connect();
    $result = mysqli_query($this->__conn, $sql);
    if (!$result) {
      die('Câu truy vấn bị sai');
    }
    $return = array();
    while ($row = mysqli_fetch_assoc($result)) {
      $return[] = $row;
    }
    mysqli_free_result($result);
    return $return;
  }
  public function get_row($sql) {
    $this->connect();
    $result = mysqli_query($this->__conn, $sql);
    if (!$result) {
      die('Câu truy vấn bị sai');
    }
    $row = mysqli_fetch_assoc($result);
    mysqli_free_result($result);
    if ($row) {
      return $row;
    }
    return false;
  }
}
?>

C:\xampp\htdocs\php\demo.php

<?php  
	require ('DB_driver.php');
	$DB = new DB_driver();
	$DB->insert('customer', array(
    'name' => 'Nguyễn Văn Cường',
    'phone' => '0979306603'
	));
?>
CREATE TABLE IF NOT EXISTS `customer` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL,
  `phone` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

Last updated