本文實(shí)例講述了PHP實(shí)現(xiàn)基于mysqli的Model基類。分享給大家供大家參考,具體如下:
DB.class.php:
<?php
//數(shù)據(jù)庫(kù)連接類
class DB {
//獲取對(duì)象句柄
static public function getDB() {
$_mysqli = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
if (mysqli_connect_errno()) {
echo '數(shù)據(jù)庫(kù)連接錯(cuò)誤!錯(cuò)誤代碼:'.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:
<?php
//模型基類
class Model {
//執(zhí)行多條SQL語句
public function multi($_sql) {
$_db = DB::getDB();
$_db->multi_query($_sql);
DB::unDB($_result = null, $_db);
return true;
}
//獲取下一個(gè)增值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];
}
//查找單個(gè)數(shù)據(jù)模型
protected function one($_sql) {
$_db = DB::getDB();
$_result = $_db->query($_sql);
$_objects = $_result->fetch_object();
DB::unDB($_result, $_db);
return Tool::htmlString($_objects);
}
//查找多個(gè)數(shù)據(jù)模型
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;
}
}
?>
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。