热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

本文实例讲述了php封装的数据库函数与用法。分享给大家供大家参考,具体如下:从Thinkphp里面抽离出来的数据库模块,感觉挺好用common.php:<?PHP***通用函数*包含配置文件if(is

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

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

common.php:

<&#63;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]) &#63; $_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]]) &#63; $_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) &#63; '' : rtrim($label) . ' ';
 if (!$strict) {
  if (ini_get('html_errors')) {
   $output = print_r($var, true);
   $output = '
' . $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); } &#63;>

config.php:

<&#63;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;
&#63;>

数据库模型类Model.class.php,放到classes/目录下:

<&#63;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'] &#63; 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限制数据库插入的条数并显示每次插入数据库之间的数据数目,以及避免重复提交的方法。同时还介绍了如何限制某一个数据库用户的并发连接数,以及设置数据库的连接数和连接超时时间的方法。最后提供了一些关于浏览器在线用户数和数据库连接数量比例的参考值。 ... [详细]
  • 在说Hibernate映射前,我们先来了解下对象关系映射ORM。ORM的实现思想就是将关系数据库中表的数据映射成对象,以对象的形式展现。这样开发人员就可以把对数据库的操作转化为对 ... [详细]
  • 本文介绍了在SpringBoot中集成thymeleaf前端模版的配置步骤,包括在application.properties配置文件中添加thymeleaf的配置信息,引入thymeleaf的jar包,以及创建PageController并添加index方法。 ... [详细]
  • 本文介绍了高校天文共享平台的开发过程中的思考和规划。该平台旨在为高校学生提供天象预报、科普知识、观测活动、图片分享等功能。文章分析了项目的技术栈选择、网站前端布局、业务流程、数据库结构等方面,并总结了项目存在的问题,如前后端未分离、代码混乱等。作者表示希望通过记录和规划,能够理清思路,进一步完善该平台。 ... [详细]
  • 本文内容为asp.net微信公众平台开发的目录汇总,包括数据库设计、多层架构框架搭建和入口实现、微信消息封装及反射赋值、关注事件、用户记录、回复文本消息、图文消息、服务搭建(接入)、自定义菜单等。同时提供了示例代码和相关的后台管理功能。内容涵盖了多个方面,适合综合运用。 ... [详细]
  • 基于layUI的图片上传前预览功能的2种实现方式
    本文介绍了基于layUI的图片上传前预览功能的两种实现方式:一种是使用blob+FileReader,另一种是使用layUI自带的参数。通过选择文件后点击文件名,在页面中间弹窗内预览图片。其中,layUI自带的参数实现了图片预览功能。该功能依赖于layUI的上传模块,并使用了blob和FileReader来读取本地文件并获取图像的base64编码。点击文件名时会执行See()函数。摘要长度为169字。 ... [详细]
  • HDU 2372 El Dorado(DP)的最长上升子序列长度求解方法
    本文介绍了解决HDU 2372 El Dorado问题的一种动态规划方法,通过循环k的方式求解最长上升子序列的长度。具体实现过程包括初始化dp数组、读取数列、计算最长上升子序列长度等步骤。 ... [详细]
  • 本文介绍了C#中数据集DataSet对象的使用及相关方法详解,包括DataSet对象的概述、与数据关系对象的互联、Rows集合和Columns集合的组成,以及DataSet对象常用的方法之一——Merge方法的使用。通过本文的阅读,读者可以了解到DataSet对象在C#中的重要性和使用方法。 ... [详细]
  • Mac OS 升级到11.2.2 Eclipse打不开了,报错Failed to create the Java Virtual Machine
    本文介绍了在Mac OS升级到11.2.2版本后,使用Eclipse打开时出现报错Failed to create the Java Virtual Machine的问题,并提供了解决方法。 ... [详细]
  • 本文详细介绍了Linux中进程控制块PCBtask_struct结构体的结构和作用,包括进程状态、进程号、待处理信号、进程地址空间、调度标志、锁深度、基本时间片、调度策略以及内存管理信息等方面的内容。阅读本文可以更加深入地了解Linux进程管理的原理和机制。 ... [详细]
  • 1,关于死锁的理解死锁,我们可以简单的理解为是两个线程同时使用同一资源,两个线程又得不到相应的资源而造成永无相互等待的情况。 2,模拟死锁背景介绍:我们创建一个朋友 ... [详细]
  • 本文介绍了在Mac上搭建php环境后无法使用localhost连接mysql的问题,并通过将localhost替换为127.0.0.1或本机IP解决了该问题。文章解释了localhost和127.0.0.1的区别,指出了使用socket方式连接导致连接失败的原因。此外,还提供了相关链接供读者深入了解。 ... [详细]
  • 动态规划算法的基本步骤及最长递增子序列问题详解
    本文详细介绍了动态规划算法的基本步骤,包括划分阶段、选择状态、决策和状态转移方程,并以最长递增子序列问题为例进行了详细解析。动态规划算法的有效性依赖于问题本身所具有的最优子结构性质和子问题重叠性质。通过将子问题的解保存在一个表中,在以后尽可能多地利用这些子问题的解,从而提高算法的效率。 ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • 本文详细介绍了MysqlDump和mysqldump进行全库备份的相关知识,包括备份命令的使用方法、my.cnf配置文件的设置、binlog日志的位置指定、增量恢复的方式以及适用于innodb引擎和myisam引擎的备份方法。对于需要进行数据库备份的用户来说,本文提供了一些有价值的参考内容。 ... [详细]
author-avatar
活宝贝aaaaaaaaaaaaa
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有