当前位置: 移动技术网 > IT编程>开发语言>PHP > php封装的数据库函数与用法示例【参考thinkPHP】

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

本文实例讲述了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+mysql数据库操作入门教程》、《php基本语法入门教程》、《php运算与运算符用法总结》、《php面向对象程序设计入门教程》、《php网络编程技巧总结》、《php数组(array)操作技巧大全》、《php字符串(string)用法总结》及《php常见数据库操作技巧汇总

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网