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

时间:2022-01-07 15:38:53

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

DB.class.php

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

Model.class.php

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

希望本文所述对大家PHP程序设计有所帮助。