从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封装数据库函数的更多相关文章

  1. Entity Framework 6 Recipes 2nd Edition(11-11)译 -> 在LINQ中调用数据库函数

    11-11. 在LINQ中调用数据库函数 问题 相要在一个LINQ 查询中调用数据库函数. 解决方案 假设有一个任命(Appointment )实体模型,如Figure 11-11.所示, 我们想要查 ...

  2. [Django]模型提高部分--聚合(group by)和条件表达式+数据库函数

    前言:本文以学习记录的形式发表出来,前段时间苦于照模型聚合中group by 找了很久,官方文章中没有很明确的说出group by,但在文档中有提到!!! 正文(最后编辑于2016-11-12): 聚 ...

  3. JSP-07-使用JavaBean封装数据

    7.1 常命包名 Dao 包中的接口(NewsDao)以及类(NewsDaoImpl)注意负责和数据操作相关的事情. Service 包中的接口和类对dao的方法进行封装和调用,注意负责和业务逻辑相关 ...

  4. PHP学习之[第09讲]PHP 的 Mysql 数据库函数 (微型博客系统)

    一.数据库函数: mysql_connect(数据库地址,用户名,密码) mysql_select_db(数据库名) mysql_set_chartset(‘编码’) //PHP5.2.3以后的函数 ...

  5. php Mysql 和Mysqli数据库函数整合

    PHP Mysql和Mysqli数据库函数整合 服务器如果支持mysqli函数将优先mysqli函数进行数据库操作 否则将调用mysql函数进行数据库操作 用法SQL::connect(host,us ...

  6. json和xml封装数据、数据缓存到文件中

    一.APP的通信格式之xml xml:扩展标记语言,可以用来标记数据,定义数据类型,是一种允许用户对自己标记语言进行定义的源语言.XML格式统一,扩平台语言,非常适合数据传输和通信,业界公认的标准. ...

  7. 预先封装数据的思路.md

    预先封装数据的思路.md python3 最近有两位同学开发开发了用程序在线竞猜数字的小游戏,可以通过以下两个网址去玩: bbaa的游戏 http://bbaass.tk/math/ codetige ...

  8. xml方式封装数据方法

    1.xml方式封装数据方法 2.demo <?php xml方式封装数据方法 /** * [xmlEncode description] * @param [type] $code [descr ...

  9. 关于双重for循环封装数据问题

    1.问题描述 在使用双重for循环进行封装数据时出现一个问题,就是有的数据封装上了,有的数据未封装上,找了很久原因: for (A a:ListA) { for (B b: ListB) { if(a ...

随机推荐

  1. 关于Promise的一些个人理解jQuery的deferred

      一.什么是deferred对象? 开发网站的过程中,我们经常遇到某些耗时很长的javascript操作.其中,既有异步的操作(比如ajax读取服务器数据),也有同步的操作(比如遍历一个大型数组), ...

  2. logstash启动脚本

    1  nohup ./redis-server 1>log.log 2>error.log &  2 nohup ./elasticsearch -f & 3 nohup ...

  3. 视频播放代码 crastr3

    下载:http://down.51cto.com/data/1904974 代码(亲测): <html xmlns="http://www.w3.org/1999/xhtml" ...

  4. springmvc转换JSON数据

    1.引入jackson包 要想在springmvc框架下支持json的转换,需要引入jackson的包,在pom.xml中添加如下代码: <dependency> <groupId& ...

  5. C#常用特性

    1.服务器控件ID .NET服务器控件有三个ID,即:ID,ClientID和UniqueID ID为服务器控件的服务器标示,在服务器代码中通过ID来唯一区分服务器控件: ClientID是服务器控件 ...

  6. UART,SPI,IIC的一点理解

    转自:http://bbs.21ic.com/icview-253715-1-1.html UART通用异步收发器,UART是通用的异步传输模式,在它这种基础上加上其他接口或者解码器就衍生出多种异步传 ...

  7. POSTGRESQL 查看用户使用情况以及杀掉相应的进程

    一.查看哪些用户在链接数据库 select * from pg_stat_activity ; 这里的pg_stat_activity其实是一个视图,它的定义可以在postgres这个数据库里面的视图 ...

  8. android N : UnsatisfiedLinkError 只能访问设置为公用库的so库

    在android N上使用 .so作为apk的第三方库的时候,会发生java.lang.UnsatisfiedLinkError: 09-27 12:17:01.280 D/ListenSoundMo ...

  9. [Nginx]用Nginx实现与应用结合的訪问控制 - 防盗链

    应用场景:图片等资源须要设置权限,如:仅仅有认证过的用户才干訪问自己的图片. 解决的方法:使用Nginx的防盗链模块http_secure_link能够实现,该模块默认情况下不包括.故在安装时要加上- ...

  10. WinHttp编写HTTP服务器示例代码

    这是微软提供的示例程序,原文地址在此https://msdn.microsoft.com/en-us/library/windows/desktop/aa364640(v=vs.85).aspx HT ...