侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

ThinkPHP  /  管理员 发布于 8年前   411

本文实例讲述了php封装的数据库函数与用法。分享给大家供大家参考,具体如下:

从Thinkphp里面抽离出来的数据库模块,感觉挺好用

common.php:

' . $label . htmlspecialchars($output, ENT_QUOTES) . '
'; } 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 = '
' . $label . htmlspecialchars($output, ENT_QUOTES) . '
'; } } if ($echo) { echo($output); return null; } else return $output;}/** * 调试输出 * @param type $msg */function _debug($msg) { if (C("debug")) echo "$msg
";}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:

 '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/目录下:

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程序设计有所帮助。

您可能感兴趣的文章:

  • Thinkphp5结合layer弹窗定制操作结果页面
  • PHP实现的简单留言板功能示例【基于thinkPHP框架】
  • thinkphp5.0整合phpsocketio完整攻略(绕坑)
  • ThinkPHP5邮件发送服务封装(可发附件)
  • 封装ThinkPHP的一个文件上传方法实例
  • thinkphp中连接oracle时封装方法无法用的解决办法
  • thinkPHP框架中layer.js的封装与使用方法示例


  • 上一条:
    thinkPHP批量删除的实现方法分析
    下一条:
    php执行多个存储过程的方法【基于thinkPHP】
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • thinkphp + mongodb项目中数据加载慢问题分析及解决(0个评论)
    • thinkphp6框架中封装redis操作类(0个评论)
    • thinkphp6框架中实现定时任务功能流程步骤(0个评论)
    • Thinkphp5.1框架中实现Session+Redis会话共享流程步骤(0个评论)
    • TP5框架版本5.0.10安全漏洞根据官方补丁修复,也是本站安全漏洞修复(0个评论)
    • 近期文章
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2017-07
    • 2017-08
    • 2017-09
    • 2017-10
    • 2017-12
    • 2018-01
    • 2018-02
    • 2020-03
    • 2021-07
    • 2021-12
    • 2022-05
    • 2022-06
    • 2022-09
    • 2023-01
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客