PHP encapsulates Db classes and simple application examples similar to thinkphp coherent operation database

  • 2021-12-09 08:31:36
  • OfStack

PHP encapsulation similar to thinkphp coherent operation database Db class and simple application are described in this paper. Share it for your reference, as follows:


<?php
header("Content-Type:text/html;charset=utf-8");
/**
 *php Operation mysql Tool class of 
 */
class Db{
  private $_db = null;// Database connection handle 
  private $_table = null;// Table name 
  private $_where = null;//where Condition 
  private $_order = null;//order Sort 
  private $_limit = null;//limit Qualified query 
  private $_group = null;//group Grouping 
  private $_configs = array(
        'hostname' => 'localhost',
        'dbname'  => 'test',
        'username' => 'root',
        'password' => '1234'
      );// Database configuration 
  /**
   *  Constructor to connect to the database 
   */
  public function __construct(){
    $link = $this->_db;
    if(!$link){
      $db = mysqli_connect($this->_configs['hostname'],$this->_configs['username'],$this->_configs['password'],$this->_configs['dbname']);
      mysqli_query($db,"set names utf8");
      if(!$db){
        $this->ShowException(" Error message ".mysqli_connect_error());
      }
      $this->_db = $db;
    }
  }
  /**
   *  Get all data 
   *
   * @param   <type>  $table The table
   *
   * @return   boolean All.
   */
  public function getAll($table=null){
    $link = $this->_db;
    if(!$link)return false;
    $sql = "SELECT * FROM {$table}";
    $data = mysqli_fetch_all($this->execute($sql));
    return $data;
  }
  public function table($table){
    $this->_table = $table;
    return $this;
  }
  /**
   *  Implement query operation 
   *
   * @param   string  $fields The fields
   *
   * @return   boolean ( description_of_the_return_value )
   */
  public function select($fields="*"){
    $fieldsStr = '';
    $link = $this->_db;
    if(!$link)return false;
    if(is_array($fields)){
      $fieldsStr = implode(',', $fields);
    }elseif(is_string($fields)&&!empty($fields)){
      $fieldsStr = $fields;
    }
    $sql = "SELECT {$fields} FROM {$this->_table} {$this->_where} {$this->_order} {$this->_limit}";
    $data = mysqli_fetch_all($this->execute($sql));
    return $data;
  }
  /**
   * order Sort 
   *
   * @param   string  $order The order
   *
   * @return   boolean ( description_of_the_return_value )
   */
  public function order($order=''){
    $orderStr = '';
    $link = $this->_db;
    if(!$link)return false;
    if(is_string($order)&&!empty($order)){
      $orderStr = "ORDER BY ".$order;
    }
    $this->_order = $orderStr;
    return $this;
  }
  /**
   * where Condition 
   *
   * @param   string $where The where
   *
   * @return   <type> ( description_of_the_return_value )
   */
  public function where($where=''){
    $whereStr = '';
    $link = $this->_db;
    if(!$link)return $link;
    if(is_array($where)){
      foreach ($where as $key => $value) {
        if($value == end($where)){
          $whereStr .= "`".$key."` = '".$value."'";
        }else{
          $whereStr .= "`".$key."` = '".$value."' AND ";
        }
      }
      $whereStr = "WHERE ".$whereStr;
    }elseif(is_string($where)&&!empty($where)){
      $whereStr = "WHERE ".$where;
    }
    $this->_where = $whereStr;
    return $this;
  }
  /**
   * group Grouping 
   *
   * @param   string  $group The group
   *
   * @return   boolean ( description_of_the_return_value )
   */
  public function group($group=''){
    $groupStr = '';
    $link = $this->_db;
    if(!$link)return false;
    if(is_array($group)){
      $groupStr = "GROUP BY ".implode(',',$group);
    }elseif(is_string($group)&&!empty($group)){
      $groupStr = "GROUP BY ".$group;
    }
    $this->_group = $groupStr;
    return $this;
  }
  /**
   * limit Qualified query 
   *
   * @param   string $limit The limit
   *
   * @return   <type> ( description_of_the_return_value )
   */
  public function limit($limit=''){
    $limitStr = '';
    $link = $this->_db;
    if(!$link)return $link;
    if(is_string($limit)||!empty($limit)){
      $limitStr = "LIMIT ".$limit;
    }elseif(is_numeric($limit)){
      $limitStr = "LIMIT ".$limit;
    }
    $this->_limit = $limitStr;
    return $this;
  }
  /**
   *  Execute sql Statement 
   *
   * @param   <type>  $sql  The sql
   *
   * @return   boolean ( description_of_the_return_value )
   */
  public function execute($sql=null){
    $link = $this->_db;
    if(!$link)return false;
    $res = mysqli_query($this->_db,$sql);
    if(!$res){
      $errors = mysqli_error_list($this->_db);
      $this->ShowException(" Wrong report! <br/> Error number: ".$errors[0]['errno']."<br/>SQL Error status: ".$errors[0]['sqlstate']."<br/> Error message: ".$errors[0]['error']);
      die();
    }
    return $res;
  }
  /**
   *  Insert data 
   *
   * @param   <type>  $data  The data
   *
   * @return   boolean ( description_of_the_return_value )
   */
  public function insert($data){
    $link = $this->_db;
    if(!$link)return false;
    if(is_array($data)){
      $keys = '';
      $values = '';
      foreach ($data as $key => $value) {
        $keys .= "`".$key."`,";
        $values .= "'".$value."',";
      }
      $keys = rtrim($keys,',');
      $values = rtrim($values,',');
    }
    $sql = "INSERT INTO `{$this->_table}`({$keys}) VALUES({$values})";
    mysqli_query($this->_db,$sql);
    $insertId = mysqli_insert_id($this->_db);
    return $insertId;
  }
  /**
   *  Update data 
   *
   * @param   <type> $data  The data
   *
   * @return   <type> ( description_of_the_return_value )
   */
  public function update($data){
    $link = $this->_db;
    if(!$link)return $link;
    if(is_array($data)){
      $dataStr = '';
      foreach ($data as $key => $value) {
        $dataStr .= "`".$key."`='".$value."',";
      }
      $dataStr = rtrim($dataStr,',');
    }
    $sql = "UPDATE `{$this->_table}` SET {$dataStr} {$this->_where} {$this->_order} {$this->_limit}";
    $res = $this->execute($sql);
    return $res;
  }
  /**
   *  Delete data 
   *
   * @return   <type> ( description_of_the_return_value )
   */
  public function delete(){
    $link = $this->_db;
    if(!$link)return $link;
    $sql = "DELETE FROM `{$this->_table}` {$this->_where}";
    $res = $this->execute($sql);
    return $res;
  }
  /**
   *  Output of abnormal information 
   *
   * @param   <type> $var  The variable
   */
  private function ShowException($var){
    if(is_bool($var)){
      var_dump($var);
    }else if(is_null($var)){
      var_dump(NULL);
    }else{
      echo "<pre style='position:relative;z-index:1000;padding:10px;border-radius:5px;background:#F5F5F5;border:1px solid #aaa;font-size:14px;line-height:18px;opacity:0.9;'>".print_r($var,true)."</pre>";
    }
  }
}
$db = new Db();
// Query operation 
var_dump($db->table('user')->where('id > 2')->order('id desc')->limit('2,4')->select());
// Insert operation 
var_dump($db->table('user')->insert(array('username'=>'user','password'=>'pwd')));
// Update operation 
var_dump($db->table('user')->where('id = 1')->update(array('username'=>'user1','password'=>'pwd1')));
// Delete operation 
var_dump($db->table('user')->where('id = 1')->delete());

For more readers interested in PHP related content, please check the topics on this site: "Summary of php+mysqli Database Programming Skills", "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Syntax", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation Skills" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: