php封装的数据库函数与用法示例【参考thinkPHP】


Posted in PHP onNovember 08, 2016

本文实例讲述了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);
}

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

PHP 相关文章推荐
DEDE采集大师官方留后门的删除办法
Jan 08 PHP
关于js和php对url编码的处理方法
Mar 04 PHP
2个自定义的PHP in_array 函数,解决大量数据判断in_array的效率问题
Apr 08 PHP
支持生僻字且自动识别utf-8编码的php汉字转拼音类
Jun 27 PHP
PHP实现的连贯操作、链式操作实例
Jul 08 PHP
PHP会话控制:Session与Cookie详解
Sep 27 PHP
使用PHP和JavaScript判断请求是否来自微信内浏览器
Aug 18 PHP
Zend Framework缓存Cache用法简单实例
Mar 19 PHP
PHP获取网页所有连接的方法(附demo源码下载)
Mar 30 PHP
PHP实现链式操作的原理详解
Sep 16 PHP
PHP7使用ODBC连接SQL Server2008 R2数据库示例【基于thinkPHP5.1框架】
May 06 PHP
php探针使用原理和技巧讲解
Sep 17 PHP
php基于curl重写file_get_contents函数实例
Nov 08 #PHP
php发送http请求的常用方法分析
Nov 08 #PHP
php curl中gzip的压缩性能测试实例分析
Nov 08 #PHP
php执行多个存储过程的方法【基于thinkPHP】
Nov 08 #PHP
php实现的http请求封装示例
Nov 08 #PHP
PHP实现原生态图片上传封装类方法
Nov 08 #PHP
php使用FFmpeg接口获取视频的播放时长、码率、缩略图以及创建时间
Nov 07 #PHP
You might like
用来解析.htgroup文件的PHP类
2012/09/05 PHP
PHP抽象类和接口用法实例详解
2019/07/20 PHP
PHP大文件分割分片上传实现代码
2020/12/09 PHP
不要小看注释掉的JS 引起的安全问题
2008/12/27 Javascript
跟我学Node.js(四)---Node.js的模块载入方式与机制
2014/06/04 Javascript
让html页面不缓存js的实现方法
2014/10/31 Javascript
jquery实现兼容IE8的异步上传文件
2015/06/15 Javascript
js的flv视频播放器插件使用方法
2015/06/23 Javascript
七个不允许错过的jQuery小技巧
2015/12/21 Javascript
jQuery实现网页顶部固定导航效果代码
2015/12/24 Javascript
JavaScript中实现键值对应的字典与哈希表结构的示例
2016/06/12 Javascript
微信小程序 Button 组件详解及简单实例
2017/01/10 Javascript
Bootstrap table简单使用总结
2017/02/15 Javascript
CodeMirror js代码加亮使用总结
2017/03/25 Javascript
JavaScript之浏览器对象_动力节点Java学院整理
2017/07/03 Javascript
浅谈React组件之性能优化
2018/03/02 Javascript
简单介绍react redux的中间件的使用
2018/04/06 Javascript
搭建一个Koa后端项目脚手架的方法步骤
2019/05/30 Javascript
vue登录页面cookie的使用及页面跳转代码
2019/07/10 Javascript
layer.open 获取不到表单信息的解决方法
2019/09/26 Javascript
使用layer模态框给新页面传值的方法
2019/09/27 Javascript
纯js+css实现仿移动端淘宝网站的弹出详情框功能
2019/12/29 Javascript
extjs4图表绘制之折线图实现方法分析
2020/03/06 Javascript
深入浅析vue全局环境变量和模式
2020/04/28 Javascript
[36:33]完美世界DOTA2联赛循环赛 Matador vs Forest 第一场 11.06
2020/11/06 DOTA
Python中的random()方法的使用介绍
2015/05/15 Python
Python网络编程中urllib2模块的用法总结
2016/07/12 Python
python将字典内容存入mysql实例代码
2018/01/18 Python
Python3常用内置方法代码实例
2019/11/18 Python
jupyter notebook更换皮肤主题的实现
2021/01/07 Python
金士达面试非笔试
2012/03/14 面试题
小学少先队活动方案
2014/02/18 职场文书
年度安全生产目标责任书
2014/07/23 职场文书
2014审计局领导班子民主生活会对照检查材料思想汇报
2014/09/20 职场文书
家长反馈意见及建议
2015/06/03 职场文书
2015年学校医务室工作总结
2015/07/20 职场文书