A-A+

PHP实现基于mysqli的Model基类完整实例

2019年10月16日 我爱编程 暂无评论

本文实例讲述了PHP实现基于mysqli的Model基类。分享给大家供大家参考,具体如下:

DB.class.php

  1. <?php
  2.   //数据库连接类
  3.   class DB {
  4.      //获取对象句柄
  5.      static public function getDB() {
  6.        $_mysqli = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
  7.        if (mysqli_connect_errno()) {
  8.           echo '数据库连接错误!错误代码:'.mysqli_connect_error();
  9.           exit();
  10.        }
  11.        $_mysqli->set_charset('utf8');
  12.        return $_mysqli;
  13.      }
  14.      //清理,释放资源
  15.      static public function unDB(&$_result, &$_db) {
  16.        if (is_object($_result)) {
  17.           $_result->free();
  18.           $_result = null;
  19.        }
  20.        if (is_object($_db)) {
  21.           $_db->close();
  22.           $_db = null;
  23.        }
  24.      }
  25.   }
  26. ?>

Model.class.php

  1. <?php
  2.   //模型基类
  3.   class Model {
  4.      //执行多条SQL语句
  5.      public function multi($_sql) {
  6.        $_db = DB::getDB();
  7.        $_db->multi_query($_sql);
  8.        DB::unDB($_result = null, $_db);
  9.        return true;
  10.      }
  11.      //获取下一个增值id模型
  12.      public function nextid($_table) {
  13.        $_sql = "SHOW TABLE STATUS LIKE '$_table'";
  14.        $_object = $this->one($_sql);
  15.        return $_object->Auto_increment;
  16.      }
  17.      //查找总记录模型
  18.      protected function total($_sql) {
  19.        $_db = DB::getDB();
  20.        $_result = $_db->query($_sql);
  21.        $_total = $_result->fetch_row();
  22.        DB::unDB($_result$_db);
  23.        return $_total[0];
  24.      }
  25.      //查找单个数据模型
  26.      protected function one($_sql) {
  27.        $_db = DB::getDB();
  28.        $_result = $_db->query($_sql);
  29.        $_objects = $_result->fetch_object();
  30.        DB::unDB($_result$_db);
  31.        return Tool::htmlString($_objects);
  32.      }
  33.      //查找多个数据模型
  34.     protected function all($_sql) {
  35.        $_db = DB::getDB();
  36.        $_result = $_db->query($_sql);
  37.        $_html = array();
  38.        while (!!$_objects = $_result->fetch_object()) {
  39.           $_html[] = $_objects;
  40.        }
  41.        DB::unDB($_result$_db);
  42.        return Tool::htmlString($_html);
  43.      }
  44.      //增删修模型
  45.      protected function aud($_sql) {
  46.        $_db = DB::getDB();
  47.        $_db->query($_sql);
  48.        $_affected_rows = $_db->affected_rows;
  49.        DB::unDB($_result = null, $_db);
  50.        return $_affected_rows;
  51.      }
  52.   }
  53. ?>
标签:

给我留言

Copyright © 四季博客 保留所有权利.   Theme  Ality

用户登录