欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

php封裝的數(shù)據(jù)庫函數(shù)與用法示例【參考thinkPHP】

 更新時間:2016年11月08日 14:20:18   作者:ifeixiang  
這篇文章主要介紹了php封裝的數(shù)據(jù)庫函數(shù)與用法,基于thinkPHP中數(shù)據(jù)庫操作相關代碼整理簡化而來,包括針對數(shù)據(jù)庫的設置、連接、查詢及日志操作等功能,簡單實用,需要的朋友可以參考下

本文實例講述了php封裝的數(shù)據(jù)庫函數(shù)與用法。分享給大家供大家參考,具體如下:

從Thinkphp里面抽離出來的數(shù)據(jù)庫模塊,感覺挺好用

common.php:

<?PHP
/**
 * 通用函數(shù)
 */
//包含配置文件
if (is_file("config.php")) {
 C(include 'config.php');
}
if (!function_exists("__autoload")) {
 function __autoload($class_name) {
  require_once('classes/' . $class_name . '.class.php');
 }
}
/**
 * 數(shù)據(jù)庫操作函數(shù)
 * @return \mysqli
 */
function M() {
 $db = new Model();
 if (mysqli_connect_errno())
  throw_exception(mysqli_connect_error());
 return $db;
}
// 獲取配置值
function C($name = null, $value = null) {
 //靜態(tài)全局變量,后面的使用取值都是在 $)config數(shù)組取
 static $_config = array();
 // 無參數(shù)時獲取所有
 if (empty($name))
  return $_config;
 // 優(yōu)先執(zhí)行設置獲取或賦值
 if (is_string($name)) {
  if (!strpos($name, '.')) {
   $name = strtolower($name);
   if (is_null($value))
    return isset($_config[$name]) ? $_config[$name] : null;
   $_config[$name] = $value;
   return;
  }
  // 二維數(shù)組設置和獲取支持
  $name = explode('.', $name);
  $name[0] = strtolower($name[0]);
  if (is_null($value))
   return isset($_config[$name[0]][$name[1]]) ? $_config[$name[0]][$name[1]] : null;
  $_config[$name[0]][$name[1]] = $value;
  return;
 }
 // 批量設置
 if (is_array($name)) {
  return $_config = array_merge($_config, array_change_key_case($name));
 }
 return null; // 避免非法參數(shù)
}
function ajaxReturn($data = null, $message = "", $status) {
 $ret = array();
 $ret["data"] = $data;
 $ret["message"] = $message;
 $ret["status"] = $status;
 echo json_encode($ret);
 die();
}
//調(diào)試數(shù)組
function _dump($var) {
 if (C("debug"))
  dump($var);
}
// 瀏覽器友好的變量輸出
function dump($var, $echo = true, $label = null, $strict = true) {
 $label = ($label === null) ? '' : rtrim($label) . ' ';
 if (!$strict) {
  if (ini_get('html_errors')) {
   $output = print_r($var, true);
   $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
  } else {
   $output = $label . print_r($var, true);
  }
 } else {
  ob_start();
  var_dump($var);
  $output = ob_get_clean();
  if (!extension_loaded('xdebug')) {
   $output = preg_replace("/\]\=\>\n(\s+)/m", '] => ', $output);
   $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
  }
 }
 if ($echo) {
  echo($output);
  return null;
 }
 else
  return $output;
}
/**
 * 調(diào)試輸出
 * @param type $msg
 */
function _debug($msg) {
 if (C("debug"))
  echo "$msg<br />";
}
function _log($filename, $msg) {
 $time = date("Y-m-d H:i:s");
 $msg = "[$time]\n$msg\r\n";
 if (C("log")) {
  $fd = fopen($filename, "a+");
  fwrite($fd, $msg);
  fclose($fd);
 }
}
/**
 * 日志記錄
 * @param type $str
 */
function L($msg) {
 $time = date("Y-m-d H:i:s");
 $clientIP = $_SERVER['REMOTE_ADDR'];
 $msg = "[$time $clientIP] $msg\r\n";
 $log_file = C("LOGFILE");
 _log($log_file, $msg);
}
?>

config.php:

<?php
/**
 * 數(shù)據(jù)庫配置文件
 */
$db = array(
 'DB_TYPE' => 'mysql',
 'DB_HOST' => '127.0.0.1',
 'DB_NAME' => 'DB',
 'DB_USER' => 'USER',
 'DB_PWD' => 'PWD',
 'DB_PORT' => '3306',
);
return $db;
?>

數(shù)據(jù)庫模型類Model.class.php,放到classes/目錄下:

<?php
/**
 * 數(shù)據(jù)庫模型類
 */
class Model {
 // 數(shù)據(jù)庫連接ID 支持多個連接
 protected $linkID = array();
 // 當前數(shù)據(jù)庫操作對象
 protected $db = null;
 // 當前查詢ID
 protected $queryID = null;
 // 當前SQL指令
 protected $queryStr = '';
 // 是否已經(jīng)連接數(shù)據(jù)庫
 protected $connected = false;
 // 返回或者影響記錄數(shù)
 protected $numRows = 0;
 // 返回字段數(shù)
 protected $numCols = 0;
 // 最近錯誤信息
 protected $error = '';
 public function __construct() {
  $this->db = $this->connect();
 }
 /**
  * 連接數(shù)據(jù)庫方法
  */
 public function connect($config = '', $linkNum = 0) {
  if (!isset($this->linkID[$linkNum])) {
   if (empty($config))
    $config = array(
     'username' => C('DB_USER'),
     'password' => C('DB_PWD'),
     'hostname' => C('DB_HOST'),
     'hostport' => C('DB_PORT'),
     'database' => C('DB_NAME')
    );
   $this->linkID[$linkNum] = new mysqli($config['hostname'], $config['username'], $config['password'], $config['database'], $config['hostport'] ? intval($config['hostport']) : 3306);
   if (mysqli_connect_errno())
    throw_exception(mysqli_connect_error());
   $this->connected = true;
  }
  return $this->linkID[$linkNum];
 }
 /**
  * 初始化數(shù)據(jù)庫連接
  */
 protected function initConnect() {
  if (!$this->connected) {
   $this->db = $this->connect();
  }
 }
 /**
  * 獲得所有的查詢數(shù)據(jù)
  * @access private
  * @param string $sql sql語句
  * @return array
  */
 public function select($sql) {
  $this->initConnect();
  if (!$this->db)
   return false;
  $query = $this->db->query($sql);
  $list = array();
  if (!$query)
   return $list;
  while ($rows = $query->fetch_assoc()) {
   $list[] = $rows;
  }
  return $list;
 }
 /**
  * 只查詢一條數(shù)據(jù)
  */
 public function find($sql) {
  $resultSet = $this->select($sql);
  if (false === $resultSet) {
   return false;
  }
  if (empty($resultSet)) {// 查詢結果為空
   return null;
  }
  $data = $resultSet[0];
  return $data;
 }
 /**
  * 獲取一條記錄的某個字段值 , sql 由自己組織
  * 例子: $model->getField("select id from user limit 1")
  */
 public function getField($sql) {
  $resultSet = $this->select($sql);
  if (!empty($resultSet)) {
   return reset($resultSet[0]);
  }
 }
 /**
  * 執(zhí)行查詢 返回數(shù)據(jù)集
  */
 public function query($str) {
  $this->initConnect();
  if (!$this->db) {
   if (C("debug"))
    echo "connect to database error";
   return false;
  }
  $this->queryStr = $str;
  //釋放前次的查詢結果
  if ($this->queryID)
   $this->free();
  $this->queryID = $this->db->query($str);
  // 對存儲過程改進
  if ($this->db->more_results()) {
   while (($res = $this->db->next_result()) != NULL) {
    $res->free_result();
   }
  }
  //$this->debug();
  if (false === $this->queryID) {
   echo $this->error();
   return false;
  } else {
   $this->numRows = $this->queryID->num_rows;
   $this->numCols = $this->queryID->field_count;
   return $this->getAll();
  }
 }
 /**
  * 執(zhí)行語句 , 例如插入,更新操作
  * @access public
  * @param string $str sql指令
  * @return integer
  */
 public function execute($str) {
  $this->initConnect();
  if (!$this->db)
   return false;
  $this->queryStr = $str;
  //釋放前次的查詢結果
  if ($this->queryID)
   $this->free();
  $result = $this->db->query($str);
  if (false === $result) {
   $this->error();
   return false;
  } else {
   $this->numRows = $this->db->affected_rows;
   $this->lastInsID = $this->db->insert_id;
   return $this->numRows;
  }
 }
 /**
  * 獲得所有的查詢數(shù)據(jù)
  * @access private
  * @param string $sql sql語句
  * @return array
  */
 private function getAll() {
  //返回數(shù)據(jù)集
  $result = array();
  if ($this->numRows > 0) {
   //返回數(shù)據(jù)集
   for ($i = 0; $i < $this->numRows; $i++) {
    $result[$i] = $this->queryID->fetch_assoc();
   }
   $this->queryID->data_seek(0);
  }
  return $result;
 }
 /**
  * 返回最后插入的ID
  */
 public function getLastInsID() {
  return $this->db->insert_id;
 }
 // 返回最后執(zhí)行的sql語句
 public function _sql() {
  return $this->queryStr;
 }
 /**
  * 數(shù)據(jù)庫錯誤信息
  */
 public function error() {
  $this->error = $this->db->errno . ':' . $this->db->error;
  if ('' != $this->queryStr) {
   $this->error .= "\n [ SQL語句 ] : " . $this->queryStr;
  }
  //trace($this->error, '', 'ERR');
  return $this->error;
 }
 /**
  * 釋放查詢結果
  */
 public function free() {
  $this->queryID->free_result();
  $this->queryID = null;
 }
 /**
  * 關閉數(shù)據(jù)庫
  */
 public function close() {
  if ($this->db) {
   $this->db->close();
  }
  $this->db = null;
 }
 /**
  * 析構方法
  */
 public function __destruct() {
  if ($this->queryID) {
   $this->free();
  }
  // 關閉連接
  $this->close();
 }
}

例子:

#include "common.php"
function test(){
 $model = M();
 $sql = "select * from test";
 $list = $model->query($sql);
 _dump($list);
}

更多關于PHP相關內(nèi)容感興趣的讀者可查看本站專題:《php+mysql數(shù)據(jù)庫操作入門教程》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結》、《php面向對象程序設計入門教程》、《PHP網(wǎng)絡編程技巧總結》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結》及《php常見數(shù)據(jù)庫操作技巧匯總

希望本文所述對大家PHP程序設計有所幫助。

相關文章

  • php輸出圖像的方法實例分析

    php輸出圖像的方法實例分析

    這篇文章主要介紹了php輸出圖像的方法,簡單分析了php圖像輸出所涉及的常用函數(shù)并結合實例形式分析了php圖像輸出的具體實現(xiàn)方法,需要的朋友可以參考下
    2017-02-02
  • 使用ucenter實現(xiàn)多站點同步登錄的講解

    使用ucenter實現(xiàn)多站點同步登錄的講解

    今天小編就為大家分享一篇關于使用ucenter實現(xiàn)多站點同步登錄的講解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-03-03
  • php求圓周率的簡單實現(xiàn)方法

    php求圓周率的簡單實現(xiàn)方法

    這篇文章主要介紹了php求圓周率的簡單實現(xiàn)方法,涉及簡單的php數(shù)學運算技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2016-05-05
  • php foreach、while性能比較

    php foreach、while性能比較

    foreach是對數(shù)組副本進行操作(通過拷貝數(shù)組),而while則通過移動數(shù)組內(nèi)部指標進行操作,一般邏輯下認為,while應該比foreach快.
    2009-10-10
  • php數(shù)組去重的函數(shù)代碼

    php數(shù)組去重的函數(shù)代碼

    php中數(shù)組去重的小例子,供初學者參考
    2013-02-02
  • 利用PHP生成靜態(tài)html頁面的原理

    利用PHP生成靜態(tài)html頁面的原理

    現(xiàn)在很多網(wǎng)站系統(tǒng),如dedecms、phpcms、帝國等知名內(nèi)容管理系統(tǒng)都提供生成靜態(tài)頁面的功能,這不光有利于搜索引擎的抓取,而且還能有效降低服務器壓力。對于學習PHP,將要從事WEB網(wǎng)站開發(fā)的朋友們來說,了解這個功能是必須的,下面來分享一下PHP生成靜態(tài)頁面的原理。
    2016-09-09
  • PHP中使用Imagick讀取pdf并生成png縮略圖實例

    PHP中使用Imagick讀取pdf并生成png縮略圖實例

    這篇文章主要介紹了PHP中使用Imagick讀取pdf并生成png縮略圖實例,本文直接給出實現(xiàn)代碼,需要的朋友可以參考下
    2015-01-01
  • PHP 批量更新網(wǎng)頁內(nèi)容實現(xiàn)代碼

    PHP 批量更新網(wǎng)頁內(nèi)容實現(xiàn)代碼

    lost63原創(chuàng)的,批量替換內(nèi)容的php代碼
    2010-01-01
  • PHP中計算字符串相似度的函數(shù)代碼

    PHP中計算字符串相似度的函數(shù)代碼

    在php計算字符串相似度similar_text與相似度levenshtein函數(shù)的詳細介紹,下面我們詳細的介紹一下關于字符串相似度介紹
    2012-12-12
  • PHP刪除數(shù)組中指定值的元素常用方法實例分析【4種方法】

    PHP刪除數(shù)組中指定值的元素常用方法實例分析【4種方法】

    這篇文章主要介紹了PHP刪除數(shù)組中指定值的元素常用方法,結合實例形式對比分析了4種常用的數(shù)組遍歷與元素刪除方法,并總結分析了相關算法優(yōu)缺點,需要的朋友可以參考下
    2018-08-08

最新評論