本文转自:http://www.cnblogs.com/noevil/archive/2010/11/06/1870864.html

<?php

/**
 * 数据库操作类
 *
 * @author Moyo
 * @package defaultPackage
 */ class Mysql
{
        // 默认配置
        private $_config_default = array
        (
                'debug' => false,
                'host' => 'localhost:3306',
                'username' => 'root',
                'password' => '',
                'database' => 'mysql',
                'prefix' => '',
                'charset' => 'utf-8',
                'cached' => 'file://{root}/query_cache/'
        );
        public  $CACHE_HASH_SALT = 'sql.cache.uuland.org';
        public  $CLIENT_MULTI_RESULTS = 131072;
        // 配置信息
        private $_config = array();
        private $_debug = true;
        private $_host = '';
        private $_username = '';
        private $_password = '';
        private $_database = '';
        private $_prefix = '';
        private $_charset = '';
        private $_cached = '';
        private $_fc_path = '';
        private $_mc_server = '';
        // 运行时变量
        private $_dbc_handle = null;
        private $_query_handle = null;
        public  $sql = '';
        private $_cache_key = '';
        private $_result = array();
        private $_need_cache = false;
        // 数据库操作
        private $_operate = '';
        private $_column = '';
        private $_where = array();
        private $_order = array();
        private $_limit = '';
        private $_data = array();
        private $_cache = '';
        // 调试记录
        private $_trace = array();
        // 获取实例
        public function getInstance()
        {
                return new self();
        }
        // 私有化构造函数,禁止外部实例化
        private function __construct(){}
        // 卸载实例时,自动释放资源,关闭连接
        public function __destruct()
        {
                // 释放资源
                $this->free();
                // 关闭连接
                $this->close();
        }
        // 载入配置
        public function config($config)
        {
                $this->trace('public::config::load');
                $this->_config = $config;
                // 执行初始化
                $this->init();
        }
        // 初始化
        private function init()
        {
                $this->trace('private::config::init_default');
                // 配置分析
                foreach ($this->_config as $key => $val)
                {
                        $mkey = '_'.$key;
                        $this->$mkey = isset($this->_config[$key]) ? $this->_config[$key] : $this->_config_default[$key];
                }
                // 清理非debug模式下,之前记录的调试信息
                if (!$this->_debug) unset($this->_trace);
                // 缓存配置
                $this->trace('private::config::init_cache');
                $cache_conf = explode('://', $this->_cached);
                $this->_cached = $cache_conf[0];
                if ($this->_cached == 'file')
                {
                        $this->_fc_path = str_replace('{current}', dirname(__FILE__), str_replace('{root}', $_SERVER['DOCUMENT_ROOT'], $cache_conf[1]));
                        // 检测目录
                        if (!is_dir($this->_fc_path))
                        {
                                mkdir($this->_fc_path);
                        }
                }
                elseif ($this->_cached == 'memcache')
                {
                        $this->_mc_server = $cache_conf[1];
                }
                unset($this->_config);
        }
        // 连接至数据库
        private function connect()
        {
                $this->trace('public::server::connect');
                // 连接服务器
                $this->_dbc_handle = mysql_connect(
                        $this->_host,
                        $this->_username,
                        $this->_password,
                        true,
                        $this->CLIENT_MULTI_RESULTS
                );
                if (!$this->_dbc_handle)
                {
                        $this->alert('Can\'t connect to Server [ '.$this->_username.'@'.$this->_host.' ]');
                        return false;
                }
                // 选择数据库
                if (!mysql_select_db($this->_database, $this->_dbc_handle))
                {
                        $this->alert('Can\'t select database ['.$this->_database.']');
                        return false;
                }
                $version = mysql_get_server_info($this->_dbc_handle);
                // 设置数据库编码
                if ($version >= '4.1')
                {
                        //使用UTF8存取数据库 需要mysql 4.1.0以上支持
                        mysql_query('SET NAMES "'.$this->_charset.'"', $this->_dbc_handle);
                }
                //设置 sql_model
                if($version > '5.0.1')
                {
                        mysql_query('SET SQL_Mode=""', $this->_dbc_handle);
                }
                return true;
        }
        // 释放数据查询
        private function free()
        {
                $this->trace('public::query::free');
                if ($this->_query_handle && $this->_operate == 'SELECT')
                {
                        mysql_free_result($this->_query_handle);
                }
                unset($this->_query_handle);
                unset($this->_operate);
                unset($this->_column);
                unset($this->_where);
                unset($this->_order);
                unset($this->_limit);
                unset($this->_data);
                unset($this->_cache);
                unset($this->_result);
                return true;
        }
        // 关闭数据库连接
        private function close()
        {
                if ($this->_dbc_handle)
                {
                        $this->trace('public::server::close');
                        mysql_close($this->_dbc_handle);
                        unset($this->_dbc_handle);
                }
        }
        // <![数据库操作][
        // 增改删查
        public function select($column)
        {
                $this->_operate = 'SELECT';
                $this->_column = $column;
                return $this;
        }
        public function update($column)
        {
                $this->_operate = 'UPDATE';
                $this->_column = $column;
                return $this;
        }
        public function insert($column)
        {
                $this->_operate = 'INSERT';
                $this->_column = $column;
                return $this;
        }
        public function delete($column)
        {
                $this->_operate = 'DELETE';
                $this->_column = $column;
                return $this;
        }
        // 条件
        public function where($where)
        {
                $this->_where[] = $where;
                return $this;
        }
        // 排序
        public function order($order)
        {
                $this->_order[] = $order;
                return $this;
        }
        // 限制返回结果数
        public function limit($limit)
        {
                $this->_limit = $limit;
                return $this;
        }
        // 数据存储
        public function data($data)
        {
                $this->_data[] = $data;
                return $this;
        }
        // 缓存设置
        public function cache($cache)
        {
                $this->_cache = $cache;
                return $this;
        }
        // 开始执行操作
        public function done()
        {
                $this->trace('public::query::init');
                // 数据表
                $column = $this->_prefix.$this->_column;
                // 组合SQL
                switch ($this->_operate)
                {
                        case 'SELECT':
                                $sql = 'SELECT * FROM `'.$column.'`'.$this->pack_where().$this->pack_order().$this->pack_limit();
                                break;
                        case 'UPDATE':
                                $sql = 'UPDATE `'.$column.'`'.$this->pack_data().$this->pack_where();
                                break;
                        case 'INSERT':
                                $sql = 'INSERT INTO `'.$column.'`'.$this->pack_data();
                                break;
                        case 'DELETE':
                                $sql = 'DELETE FROM `'.$column.'`'.$this->pack_where();
                                break;
                        default: break;
                }
                $this->sql = $sql;
                // 缓存判断 [暂时只支持缓存查询]
                if ($this->_operate == 'SELECT' && $this->cache_check())
                {
                        $return = $this->_result;
                        // 清理变量池并返回
                        if ($this->free()) return $return;
                }
                // 连接判断
                if (!$this->_dbc_handle) $this->connect();
                // 开始执行SQL
                $this->trace('public::query::begin['.$this->_operate.']');
                $this->_query_handle = mysql_query($sql, $this->_dbc_handle);
                if (!$this->_query_handle)
                {
                        $this->alert('SQL run error.');
                }
                $this->trace('public::query::finish['.$this->_operate.']');
                if ($this->_operate == 'SELECT')
                {
                        if (mysql_num_rows($this->_query_handle) > 0)
                        {
                                while ($one_row = mysql_fetch_assoc($this->_query_handle))
                                {
                                        $this->_result[] = $one_row;
                                }
                                mysql_data_seek($this->_query_handle, 0);
                        }
                        else
                        {
                                $this->_result = null;
                        }
                        // 写缓存
                        if ($this->_need_cache) $this->cache_write();
                        $return = $this->_result;
                        // 清理变量池并返回
                        if ($this->free()) return $return;
                }
                else
                {
                        $return = mysql_affected_rows($this->_dbc_handle);
                        // 清理变量池并返回
                        if ($this->free()) return $return;
                }
        }
        // 返回结果限制
        private function pack_limit()
        {
                if ($this->_limit == '') return '';
                if (is_numeric($this->_limit))
                {
                        return ' LIMIT 0,'.$this->_limit;
                }
                elseif (is_string($this->_limit))
                {
                        return ' LIMIT '.$this->_limit;
                }
        }
        // 条件整合
        private function pack_where()
        {
                if (!$this->_where) return '';
                $sql_where = ' WHERE ';
                foreach ($this->_where as $where)
                {
                        if (is_array($where))
                        {
                                foreach ($where as $key => $val)
                                {
                                        if (is_numeric($val))
                                        {
                                                $sql_where .= $key.'='.$val;
                                        }
                                        elseif (is_string($val))
                                        {
                                                $sql_where .= $key.'="'.$val.'"';
                                        }
                                        $sql_where .= ' and ';
                                }
                        }
                        elseif (is_string($where))
                        {
                                $conds = explode(',', $where);
                                foreach ($conds as $one_cond)
                                {
                                        $sql_where .= $one_cond.' and ';
                                }
                        }
                }
                return substr($sql_where, 0, -5);
        }
        // 排序整合
        private function pack_order()
        {
                if (!$this->_order) return '';
                $sql_order = ' ORDER BY ';
                foreach ($this->_order as $order)
                {
                        if (is_array($order))
                        {
                                foreach ($order as $key => $type)
                                {
                                        $sql_order .= $key.' '.$type.', ';
                                }
                        }
                        elseif (is_string($order))
                        {
                                $ords = explode(',', $order);
                                foreach ($ords as $one_ord)
                                {
                                        $sql_order .= str_replace('.', ' ', $one_ord).', ';
                                }
                        }
                }
                return substr($sql_order, 0, -2);
        }
        // 数据整合
        private function pack_data()
        {
                if (!$this->_data) return '';
                $sql_data = ' SET ';
                foreach ($this->_data as $data)
                {
                        if (is_array($data))
                        {
                                foreach ($data as $key => $val)
                                {
                                        if (is_numeric($val))
                                        {
                                                $sql_data .= $key.'='.$val;
                                        }
                                        elseif (is_string($val))
                                        {
                                                $sql_data .= $key.'="'.$val.'"';
                                        }
                                        $sql_data .= ', ';
                                }
                        }
                        elseif (is_string($data))
                        {
                                $datas = explode(',', $data);
                                foreach ($datas as $one_data)
                                {
                                        $sql_data .= $one_data.', ';
                                }
                        }
                }
                return substr($sql_data, 0, -2);
        }
        // ]>
        // 缓存检测
        private function cache_check()
        {
                $this->trace('private::cache::check');
                if ($this->_cache == '') return false;
                $this->_cache_key = md5($this->sql.'@'.$this->CACHE_HASH_SALT);
                $time_calc = array
                (
                        's' => 1,
                        'm' => 60,
                        'h' => 3600,
                        'd' => 86400
                );
                $c_rule = explode(':', $this->_cache);
                $c_time = $c_rule[0];
                $c_long = (int)$c_rule[1];
                if(time() - $this->cache_time() > $time_calc[$c_time]*$c_long)
                {
                        $this->_need_cache = true;
                        return false;
                }
                $this->_result = $this->cache_read();
                return true;
        }
        // 获取时间
        private function cache_time()
        {
                $handle = 'cache_handle_'.$this->_cached.'_time';
                return $this->$handle($this->_cache_key);
        }
        // 读缓存
        private function cache_read()
        {
                $this->trace('private::cache::read');
                $handle = 'cache_handle_'.$this->_cached.'_value';
                return $this->$handle($this->_cache_key);
        }
        // 写缓存
        private function cache_write()
        {
                $this->trace('private::cache::write');
                $handle = 'cache_handle_'.$this->_cached.'_write';
                $this->$handle($this->_cache_key, $this->_result);
                $this->_need_cache = false;
        }
        // <![缓存方式][
        // 文件缓存
        private function cache_handle_file_time($key)
        {
                if (is_file($this->_fc_path.$key.'.sql'))
                {
                        return filemtime($this->_fc_path.$key.'.sql');
                }
                else
                {
                        return 0;
                }
        }
        private function cache_handle_file_value($key)
        {
                if (is_file($this->_fc_path.$key.'.sql'))
                {
                        return unserialize(file_get_contents($this->_fc_path.$key.'.sql'));
                }
                else
                {
                        return false;
                }
        }
        private function cache_handle_file_write($key, $val)
        {
                file_put_contents($this->_fc_path.$key.'.sql', serialize($val));
                return true;
        }
        // memcache 缓存 [这里做的不怎么好,不过平常也用不到memcache的 ^_^]
        private function cache_handle_memcache_time($key)
        {
                $mec = new Memcache();
                $mec->connect($this->_mc_server);
                $val = $mec->get($this->_cache_key.'_time');
                $mec->close();
                if ($val == '')
                {
                        return 0;
                }
                else
                {
                        return $val;
                }
        }
        private function cache_handle_memcache_value($key)
        {
                $mec = new Memcache();
                $mec->connect($this->_mc_server);
                $val = $mec->get($this->_cache_key.'_value');
                $mec->close();
                if ($val == '')
                {
                        return false;
                }
                else
                {
                        return $val['value'];
                }
        }
        private function cache_handle_memcache_write($key, $val)
        {
                $mec = new Memcache();
                $mec->connect($this->_mc_server);
                $mec->set($this->_cache_key.'_time', time());
                $mec->set($this->_cache_key.'_value', array('cached'=>true,'value'=>$val));
                $mec->close();
                return true;
        }
        // ]>
        // <![一些数据库维护,例如:清空删除数据库、表,数据表优化等][
        // 功能后续添加
        // ]>
        // 调试信息
        private function alert($message)
        {
                if (!$this->_debug) return;
                echo '<div style="border:2px solid #000;margin:10px;padding:10px;">';
                echo $message;
                echo '<hr/>';
                echo mysql_error();
                echo '</div>';
                exit;
        }
        // 记录调试
        private function trace($message)
        {
                if (!$this->_debug) return;
                $this->_trace[] = array('timer'=>microtime(), 'mmusage'=>memory_get_usage(), 'message'=>$message);
        }
        // 输出调试
        public function trace_output()
        {
                if (!$this->_debug) return;
                echo '<div style="border:2px solid #000;margin:10px;padding:10px;">';
                echo '<ul>';
                foreach ($this->_trace as $i => $trace)
                {
                        $timer_e = explode(' ', $trace['timer']);
                        $timer = (float)$timer_e[0];
                        $mmusage = $trace['mmusage'];
                        echo '<li>Time: '.$timer.' <font color="#0FC69D">+'.($timer-$last_timer).'</font> Memory: '.$trace['mmusage'].' <font color="#E56298">+'.($mmusage-$last_mmusage).'</font> Call: '.$trace['message'].'</li>';
                        $last_timer = $timer;
                        $last_mmusage = $mmusage;
                }
                echo '</ul>';
                echo '</div>';
        }
}
?>
  具体使用方法:     <?php
include 'class.mysql.php'; echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />'; $conf_info = array
(
        // 开启调试
        'debug'=>true,
        // MySQL主机
        'host'=>'localhost:3306',
        // 用户
        'username'=>'run',
        // 密码
        'password'=>'moyo',
        // 数据库
        'database'=>'test',
        // 数据表前缀
        'prefix' => '',
        // 数据库编码
        'charset'=>'utf8',
        // 缓存方式
        // memcache缓存协议,“://” 后面的是服务器地址
        //'cached'=>'memcache://127.0.0.1:11211'
        // 文本缓存协议,“://”后面的是缓存地址。可用的标记:{root} 站点根目录, {current} 当前脚本目录
        'cached'=>'file://{current}/query_cache/'
);
// 获取实例
$dbc = db_mysql::getInstance();
// 载入配置 [只支持数组方式]
$dbc->config($conf_info); $start = explode(' ', microtime());
$memory_start = memory_get_usage(); // 插入数据
$affect = $dbc
        // 操作表:user
        ->insert('user')
        // 支持数组方式
        ->data(array('name'=>"Moyo"))
        // 支持字符方式
        ->data('mail="moyo@mail"')
->done();
echo $dbc->sql;
echo '<p></p>';
echo 'INSERT 操作完成,影响行数:'.$affect;
echo '<hr/>';
// 修改数据
$affect = $dbc
        ->update('user')
        // 支持数组方式
        ->where(array('name'=>'Moyo'))
        // 支持字符方式
        ->where('mail="moyo@mail"')
        ->data(array('name'=>"Moyo.live", 'mail'=>'moyo@uuland'))
->done();
echo $dbc->sql;
echo '<p></p>';
echo 'UPDATE 操作完成,影响行数:'.$affect;
echo '<hr/>';
// 获取数据
$result = $dbc
        ->select('user')
        ->where('name like "%Moyo%"')
        ->order('id.desc')
        ->limit(3)
        // 使用缓存,有效时间:10秒 [单位支持:d 天,h 时, m 分, s 秒]
        ->cache('s:10')
->done();
echo $dbc->sql;
echo '<p></p>';
echo 'SELECT 完成,记录数:'.count($result);
echo '<pre>';
print_r($result);
echo '</pre>';
echo '<hr/>';
// 删除数据
$affect = $dbc
        ->delete('user')
        ->where('name="Moyo.live"')
->done();
echo $dbc->sql;
echo '<p></p>';
echo 'DELETE 操作完成,影响行数:'.$affect;
echo '<hr/>'; $finish = explode(' ', microtime());
$memory_finish = memory_get_usage(); $start = $start[1]+$start[0];
$finish = $finish[1]+$finish[0];
$time = $finish-$start;
$memory = $memory_finish-$memory_start; echo 'Trace (Time use '.$time.' Sec , Memory use '.$memory_finish.' Bytes , Incress '.$memory.' Bytes)';
echo '<hr width="30%" align="left" />';
$dbc->trace_output();
?>

[转]Php MySql Class的更多相关文章

  1. Hadoop 中利用 mapreduce 读写 mysql 数据

    Hadoop 中利用 mapreduce 读写 mysql 数据   有时候我们在项目中会遇到输入结果集很大,但是输出结果很小,比如一些 pv.uv 数据,然后为了实时查询的需求,或者一些 OLAP ...

  2. mysql每秒最多能插入多少条数据 ? 死磕性能压测

    前段时间搞优化,最后瓶颈发现都在数据库单点上. 问DBA,给我的写入答案是在1W(机械硬盘)左右. 联想起前几天infoQ上一篇文章说他们最好的硬件写入速度在2W后也无法提高(SSD硬盘) 但这东西感 ...

  3. LINUX篇,设置MYSQL远程访问实用版

    每次设置root和远程访问都容易出现问题, 总结了个通用方法, 关键在于实用 step1: # mysql -u root mysql mysql> Grant all privileges o ...

  4. nodejs进阶(6)—连接MySQL数据库

    1. 建库连库 连接MySQL数据库需要安装支持 npm install mysql 我们需要提前安装按mysql sever端 建一个数据库mydb1 mysql> CREATE DATABA ...

  5. MySQL高级知识- MySQL的架构介绍

    [TOC] 1.MySQL 简介 概述 MySQL是一个关系型数据库管理系统,由瑞典MySQL AB公司开发,目前属于Oracle公司. MySQL是一种关联数据库管理系统,将数据保存在不同的表中,而 ...

  6. 闰秒导致MySQL服务器的CPU sys过高

    今天,有个哥们碰到一个问题,他有一个从库,只要是启动MySQL,CPU使用率就非常高,其中sys占比也比较高,具体可见下图. 注意:他的生产环境是物理机,单个CPU,4个Core. 于是,他抓取了CP ...

  7. 我的MYSQL学习心得(一) 简单语法

    我的MYSQL学习心得(一) 简单语法 我的MYSQL学习心得(二) 数据类型宽度 我的MYSQL学习心得(三) 查看字段长度 我的MYSQL学习心得(四) 数据类型 我的MYSQL学习心得(五) 运 ...

  8. Entity Framework Core 实现MySQL 的TimeStamp/RowVersion 并发控制

    将通用的序列号生成器库 从SQL Server迁移到Mysql 遇到的一个问题,就是TimeStamp/RowVersion并发控制类型在非Microsoft SQL Server数据库中的实现.SQ ...

  9. Docker笔记一:基于Docker容器构建并运行 nginx + php + mysql ( mariadb ) 服务环境

    首先为什么要自己编写Dockerfile来构建 nginx.php.mariadb这三个镜像呢?一是希望更深入了解Dockerfile的使用,也就能初步了解docker镜像是如何被构建的:二是希望将来 ...

  10. 当忘记mysql数据库密码时如何进行修改

    因为长时间没有使用数据库了,或者把密码改完之后就忘了数据库密码,不能正常进入数据库,也无法修改密码,有一个简单的常用修改密码方式: 1.首先找到和打开mysql.exe和mysqld.exe所在的文件 ...

随机推荐

  1. Input系统—ANR原理分析(转)

    一. 概述 当input事件处理得慢就会触发ANR,那ANR内部原理是什么,哪些场景会产生ANR呢. “工欲善其事必先利其器”,为了理解input ANR原理,前面几篇文章疏通了整个input框架的处 ...

  2. Android消息机制1-Handler(Java层)(转)

    转自:http://gityuan.com/2015/12/26/handler-message-framework/ 相关源码 framework/base/core/java/andorid/os ...

  3. 程序运行中(BSS段、数据段、代码段、堆栈)

    程序运行中(BSS段.数据段.代码段.堆栈) BSS段:(bss segment)通常是指用来存放程序中未初始化的全局变量的一块内存区域.BSS是英文Block Started by Symbol的简 ...

  4. Django项目开发-小技巧

    当你开发完一个Django项目之后肯定要吧他丢到服务器让跑起来,但是你在自己的环境下安装了好多的包,是不是在服务器中也要一个个的安装了, pip freeze > read.txt #这条命令会 ...

  5. 找不到或无法加载主类 ide 正常执行,但是打包jar后报错 maven 引入本地包

    错误: 找不到或无法加载主类 com.myali.TTSmy 问题原因: ide中编译能找到相关包,但是,打包成jar时,本地的jar引入失败 maven将系统用到的包从线上maven仓库下载到本地的 ...

  6. Linux下使用putty进行UART串口调试【转】

    本文转载自:http://blog.csdn.net/xzongyuan/article/details/11593101 版权声明:本文为博主原创文章,未经博主允许不得转载. 使用putty进行串口 ...

  7. POJ3692 Kindergarten —— 二分图最大团

    题目链接:http://poj.org/problem?id=3692 Kindergarten Time Limit: 2000MS   Memory Limit: 65536K Total Sub ...

  8. casperjs在拆分文件后的中文乱码问题的解决

    windows环境. capserjs的中文乱码使用phantom.outputEncoding="GBK";即可解决. 但当我们脚本很大,需要拆分时(参考http://docs. ...

  9. mac系统下安装mysql步骤

    1.下载mysql-5.7.13-osx10.11-x86_64.dmg安装包,并点击dmg安装包进行安装 2.安装完成后弹出如以下提示信息: 2016-06-23T01:14:48.649253Z ...

  10. gcc编译系统

    一. C语言编译过程 C语言的编译过程可分为四个阶段: 1.预处理(Preprocessing) 对源程序中的伪指令(即以#开头的指令)和特殊符号进行处理的过程. 伪指令包括:1)宏定义指令: 2)条 ...