php封裝的資料庫函數與用法

來源:互聯網
上載者:User
這篇文章主要介紹了php封裝的資料庫函數與用法,基於thinkPHP中資料庫操作相關代碼整理簡化而來,包括針對資料庫的設定、串連、查詢及日誌操作等功能,簡單實用,需要的朋友可以參考下

本文執行個體講述了php封裝的資料庫函數與用法。分享給大家供大家參考,具體如下:

從Thinkphp裡面抽離出來的資料庫模組,感覺挺好用

common.php:

<?PHP/** * 通用函數 *///包含設定檔if (is_file("config.php")) { C(include 'config.php');}if (!function_exists("__autoload")) { function __autoload($class_name) {  require_once('classes/' . $class_name . '.class.php'); }}/** * 資料庫操作函數 * @return \mysqli */function M() { $db = new Model(); if (mysqli_connect_errno())  throw_exception(mysqli_connect_error()); return $db;}// 擷取配置值function C($name = null, $value = null) { //靜態全域變數,後面的使用取值都是在 $)config數組取 static $_config = array(); // 無參數時擷取所有 if (empty($name))  return $_config; // 優先執行設定擷取或賦值 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;  }  // 二維數組設定和擷取支援  $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; // 避免非法參數}function ajaxReturn($data = null, $message = "", $status) { $ret = array(); $ret["data"] = $data; $ret["message"] = $message; $ret["status"] = $status; echo json_encode($ret); die();}//調試數組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;}/** * 調試輸出 * @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/** * 資料庫設定檔 */$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;?>

資料庫模型類Model.class.php,放到classes/目錄下:

<?php/** * 資料庫模型類 */class Model { // 資料庫連接ID 支援多個串連 protected $linkID = array(); // 當前資料庫操作對象 protected $db = null; // 當前查詢ID protected $queryID = null; // 當前SQL指令 protected $queryStr = ''; // 是否已經串連資料庫 protected $connected = false; // 返回或者影響記錄數 protected $numRows = 0; // 返回欄位數 protected $numCols = 0; // 最近錯誤資訊 protected $error = ''; public function __construct() {  $this->db = $this->connect(); } /**  * 串連資料庫方法  */ 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]; } /**  * 初始化資料庫連接  */ protected function initConnect() {  if (!$this->connected) {   $this->db = $this->connect();  } } /**  * 獲得所有的查詢資料  * @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; } /**  * 只查詢一條資料  */ 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]);  } } /**  * 執行查詢 返回資料集  */ 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();  } } /**  * 執行語句 , 例如插入,更新操作  * @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;  } } /**  * 獲得所有的查詢資料  * @access private  * @param string $sql sql語句  * @return array  */ private function getAll() {  //返回資料集  $result = array();  if ($this->numRows > 0) {   //返回資料集   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; } // 返回最後執行的sql語句 public function _sql() {  return $this->queryStr; } /**  * 資料庫錯誤資訊  */ 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; } /**  * 關閉資料庫  */ 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);}

以上就是本文的全部內容,希望對大家的學習有所協助,更多相關內容請關注topic.alibabacloud.com!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.