PHP PDO_MYSQL 链式操作 非链式操作类
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP version 5 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2004 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 3.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available through the world-wide-web at the following url: |
// | http://www.php.net/license/3_0.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Original Author <author@example.com> |
// | Your Name <you@example.com> |
// +----------------------------------------------------------------------+
//
// $Id:$ class pdomysql {
public $dbtype = 'mysql';
public $dbhost = '127.0.0.1';
public $dbport = '3306';
public $dbname = 'test';
public $dbuser = 'root';
public $dbpass = '';
public $charset = 'utf-8';
public $stmt = null;
public $DB = null;
public $connect = true; // 是否長连接
public $debug = true;
private $parms = array();
private $sql = array(
"db" => "",
"from" => "",
"where" => "",
"order" => "",
"limit" => ""
);
/**
* 构造函数
*/
public function __construct() { $this->connect();
$this->DB->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
$this->DB->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
$this->execute('SET NAMES ' . $this->charset);
}
/**
* 析构函数
*/
public function __destruct() {
$this->close();
}
/**
* *******************基本方法开始********************
*/
/**
* 作用:连結数据库
*/
public function connect() {
try {
$this->DB = new PDO($this->dbtype . ':host=' . $this->dbhost . ';port=' . $this->dbport . ';dbname=' . $this->dbname, $this->dbuser, $this->dbpass, array(
PDO::ATTR_PERSISTENT => $this->connect
));
}
catch(PDOException $e) {
die("Connect Error Infomation:" . $e->getMessage());
}
}
/**
* 关闭数据连接
*/
public function close() {
$this->DB = null;
}
/**
* 對字串進行转義
*/
public function quote($str) {
return $this->DB->quote($str);
}
/**
* 作用:获取数据表里的欄位
* 返回:表字段结构
* 类型:数组
*/
public function getFields($table) {
$this->stmt = $this->DB->query("DESCRIBE $table");
$result = $this->stmt->fetchAll(PDO::FETCH_ASSOC);
$this->stmt = null;
return $result;
}
/**
* 作用:获得最后INSERT的主鍵ID
* 返回:最后INSERT的主鍵ID
* 类型:数字
*/
public function getLastId() {
return $this->DB->lastInsertId();
}
/**
* 作用:執行INSERT\UPDATE\DELETE
* 返回:执行語句影响行数
* 类型:数字
*/
public function execute($sql) {
$this->getPDOError($sql);
return $this->DB->exec($sql);
}
/**
* 获取要操作的数据
* 返回:合併后的SQL語句
* 类型:字串
*/
private function getCode($table, $args) {
$code = '';
if (is_array($args)) {
foreach ($args as $k => $v) {
if ($v == '') {
continue;
}
$code.= "`$k`='$v',";
}
}
$code = substr($code, 0, -1);
return $code;
}
public function optimizeTable($table) {
$sql = "OPTIMIZE TABLE $table";
$this->execute($sql);
}
/**
* 执行具体SQL操作
* 返回:运行結果
* 类型:数组
*/
private function _fetch($sql, $type) {
$result = array();
$this->stmt = $this->DB->query($sql);
$this->getPDOError($sql);
$this->stmt->setFetchMode(PDO::FETCH_ASSOC);
switch ($type) {
case '0':
$result = $this->stmt->fetch();
break; case '1':
$result = $this->stmt->fetchAll();
break; case '2':
$result = $this->stmt->rowCount();
break;
}
$this->stmt = null;
return $result;
}
/**
* *******************基本方法結束********************
*/
/**
* *******************Sql操作方法开始********************
*/
/**
* 作用:插入数据
* 返回:表內記录
* 类型:数组
* 參数:$db->insert('$table',array('title'=>'Zxsv'))
*/
public function add($table, $args) {
$sql = "INSERT INTO `$table` SET ";
$code = $this->getCode($table, $args);
$sql.= $code;
return $this->execute($sql);
}
/**
* 修改数据
* 返回:記录数
* 类型:数字
* 參数:$db->up($table,array('title'=>'Zxsv'),array('id'=>'1'),$where
* ='id=3');
*/
public function up($table, $args, $where) {
$code = $this->getCode($table, $args);
$sql = "UPDATE `$table` SET ";
$sql.= $code;
$sql.= " Where $where";
return $this->execute($sql);
}
/**
* 作用:刪除数据
* 返回:表內記录
* 类型:数组
* 參数:$db->del($table,$condition = null,$where ='id=3')
*/
public function del($table, $where) {
$sql = "DELETE FROM `$table` Where $where";
return $this->execute($sql);
}
/**
* 作用:获取單行数据
* 返回:表內第一条記录
* 类型:数组
* 參数:$db->fetOne($table,$condition = null,$field = '*',$where ='')
*/
public function fetOne($table, $field = '*', $where = false) {
$sql = "SELECT {$field} FROM `{$table}`";
$sql.= ($where) ? " WHERE $where" : '';
return $this->_fetch($sql, $type = '0');
}
/**
* 作用:获取所有数据
* 返回:表內記录
* 类型:二維数组
* 參数:$db->fetAll('$table',$condition = '',$field = '*',$orderby = '',$limit
* = '',$where='')
*/
public function fetAll($table, $field = '*', $orderby = false, $where = false) {
$sql = "SELECT {$field} FROM `{$table}`";
$sql.= ($where) ? " WHERE $where" : '';
$sql.= ($orderby) ? " ORDER BY $orderby" : '';
return $this->_fetch($sql, $type = '1');
}
/**
* 作用:获取單行数据
* 返回:表內第一条記录
* 类型:数组
* 參数:select * from table where id='1'
*/
public function getOne($sql) {
return $this->_fetch($sql, $type = '0');
}
/**
* 作用:获取所有数据
* 返回:表內記录
* 类型:二維数组
* 參数:select * from table
*/
public function getAll($sql) {
return $this->_fetch($sql, $type = '1');
}
/**
* 作用:获取首行首列数据
* 返回:首行首列欄位值
* 类型:值
* 參数:select `a` from table where id='1'
*/
public function scalar($sql, $fieldname) {
$row = $this->_fetch($sql, $type = '0');
return $row[$fieldname];
}
/**
* 获取記录总数
* 返回:記录数
* 类型:数字
* 參数:$db->fetRow('$table',$condition = '',$where ='');
*/
public function fetRowCount($table, $field = '*', $where = false) {
$sql = "SELECT COUNT({$field}) AS num FROM $table";
$sql.= ($where) ? " WHERE $where" : '';
return $this->_fetch($sql, $type = '0');
}
/**
* 获取記录总数
* 返回:記录数
* 类型:数字
* 參数:select count(*) from table
*/
public function getRowCount($sql) {
return $this->_fetch($sql, $type = '2');
}
//链式操作开始
public function from($tableName) {
$this->sql["from"] = "FROM " . $tableName;
return $this;
}
public function db($tableName) {
$this->sql["db"] = $tableName;
return $this;
}
public function where($_where = '1=1') {
$this->sql["where"] = "WHERE " . $_where;
return $this;
}
public function order($_order = 'id DESC') {
$this->sql["order"] = "ORDER BY " . $_order;
return $this;
}
public function limit($_limitstart="30",$_limitend = '0') {
if ($_limitend=="0"){
$this->sql["limit"] = "LIMIT 0," . $_limitstart;
}else{
$this->sql["limit"] = "LIMIT $_limitstart," . $_limitend;
} return $this;
}
/**
* 获取所有記录
* 返回:所有記录
* 类型:array
* 參数: $pdomysql->from('dbname')->limit(30)->where('1=1')->select();
*/
public function select($_select = '*') {
//return "SELECT " . $_select . " " . (implode(" ", $this->sql));
$sql="SELECT " . $_select . " " . (implode(" ", $this->sql));
return $this->_fetch($sql, $type = '1');
}
/**
* 获取一条記录
* 返回:一条記录
* 类型:array
* 參数: $pdomysql->from('dbname')->limit(30)->where('1=1')->find();
*/
public function find($_find = '*'){
$this->sql['limit']='limit 1';
$sql="SELECT " . $_find . " " . (implode(" ", $this->sql));
return $this->_fetch($sql, $type = '0');
}
/**
* 插入一条数据
* 返回:执行结果
* 类型:bool
* 參数: $pdomysql->db('dbname')->insert(array('col1'="sadsd"));
*/
public function insert($_insert=array()){
$table=$this->sql['db'];
$sql = "INSERT INTO `$table` SET ";
$code = $this->getCode($table, $args);
$sql.= $code;
return $this->execute($sql);
}
/**
* 删除
* 返回:删除结果
* 类型:bool
* 參数: $pdomysql->from('dbname')->where('1=1')->delete();
*/
public function delete(){
$sql="DELETE " . (implode(" ", $this->sql));
return $this->execute($sql);
}
public function update(){ }
//链式操作end
/**
* *******************Sql操作方法結束********************
*/
/**
* *******************错误处理开始********************
*/
/**
* 設置是否为调试模式
*/
public function setDebugMode($mode = true) {
return ($mode == true) ? $this->debug = true : $this->debug = false;
}
/**
* 捕获PDO错误信息
* 返回:出错信息
* 类型:字串
*/
private function getPDOError($sql) {
$this->debug ? $this->errorfile($sql) : '';
if ($this->DB->errorCode() != '00000') {
$info = ($this->stmt) ? $this->stmt->errorInfo() : $this->DB->errorInfo();
echo ($this->sqlError('mySQL Query Error', $info[2], $sql));
exit();
}
}
private function getSTMTError($sql) {
$this->debug ? $this->errorfile($sql) : '';
if ($this->stmt->errorCode() != '00000') {
$info = ($this->stmt) ? $this->stmt->errorInfo() : $this->DB->errorInfo();
echo ($this->sqlError('mySQL Query Error', $info[2], $sql));
exit();
}
}
/**
* 寫入错误日志
*/
private function errorfile($sql) {
echo $sql . '<br />';
$errorfile = __DIR__ . '/dberrorlog.php';
$sql = str_replace(array(
"\n",
"\r",
"\t",
" ",
" ",
" "
) , array(
" ",
" ",
" ",
" ",
" ",
" "
) , $sql);
if (!file_exists($errorfile)) {
$fp = file_put_contents($errorfile, "<?PHP exit('Access Denied'); ?>\n" . $sql);
} else {
$fp = file_put_contents($errorfile, "\n" . $sql, FILE_APPEND);
}
}
/**
* 作用:运行错误信息
* 返回:运行错误信息和SQL語句
* 类型:字符
*/
private function sqlError($message = '', $info = '', $sql = '') {
$html = '';
if ($message) {
$html.= $message;
}
if ($info) {
$html.= 'SQLID: ' . $info;
}
if ($sql) {
$html.= 'ErrorSQL: ' . $sql;
}
throw new Exception($html);
}
/**
* *******************错误处理結束********************
*/
}
PHP PDO_MYSQL 链式操作 非链式操作类的更多相关文章
- 阻塞式和非阻塞式IO
有很多人把阻塞认为是同步,把非阻塞认为是异步:个人认为这样是不准确的,当然从思想上可以这样类比,但方式是完全不同的,下面说说在JAVA里面阻塞IO和非阻塞IO的区别 在JDK1.4中引入了一个NIO的 ...
- 多态设计 zen of python poem 显式而非隐式 延迟赋值
总结 1.python支持延迟赋值,但是给调用者带来了困惑: 2.显式而非隐式,应当显式地指定要初始化的变量 class Card: def __init__(self, rank, suit): s ...
- Spring学习(1):侵入式与非侵入式,轻量级与重量级
一. 引言 在阅读spring相关资料,都会提到Spring是非侵入式编程模型,轻量级框架,那么就有必要了解下这些概念. 二. 侵入式与非侵入式 非侵入式:使用一个新的技术不会或者基本不改变原有代码结 ...
- 如何实现XA式、非XA式Spring分布式事务
Spring应用的几种事务处理机制 Java Transaction API和XA协议是Spring常用的分布式事务机制,不过你可以选择选择其他的实现方式.理想的实现取决于你的应用程序使用何种资源,你 ...
- Boostrap响应式与非响应式
非响应式布局 在使用非响应式布局时,在<head>标签中需要加入一下内容,其中最主要的是non-responsive.css文件 <head> <meta http-eq ...
- Java基础知识强化之多线程笔记07:同步、异步、阻塞式、非阻塞式 的联系与区别
1. 同步: 所谓同步,就是在发出一个功能调用时,在没有得到结果之前,该调用就不返回.但是一旦调用返回,就必须先得到返回值了. 换句话话说,调用者主动等待这个"调用"的结果. 对于 ...
- Spring 侵入式和非侵入式
1.非侵入式的技术体现 允许在应用系统中自由选择和组装Spring框架的各个功能模块,并且不强制要求应用系统的类必须从Spring框架的系统API的某个类来继承或者实现某个接口. 2.如何实现非侵入式 ...
- 基于NIO写的阻塞式和非阻塞式的客户端服务端
由于功能太过简单,就不过多阐述了,直接上阻塞式代码: package com.lql.nio; import org.junit.Test; import java.io.IOException; i ...
- 登录式与非登录式&交互式与非交互式shell及其环境初始化过程
交互式shell和非交互式shell(interactive shell and non-interactive shell) 交互式模式就是在终端上执行,shell等待你的输入,并且立即执行你提交的 ...
随机推荐
- JS中数组实现(倒序遍历数组,数组连接字符串)
// =================== 求最大值===================================== <script> var arr = [10,35,765 ...
- 使用node.js实现多人聊天室(socket.io、B/S)
通过B/S架构实现多人聊天,客户端连接服务器,发送信息,服务器接收信息之后返回给客户端. 主要是通过socket.io实现浏览器和服务器之间进行实时,双向和基于事件的通信. socket.io官方文档 ...
- WinForm程序打包教程
准备工作 1. 编写完成的WinForm程序 2. 安装部署项 VS2010中有一个自带的安装部署项目,叫:Visual Studio Installer ,通常称为:setup项目,是一个用于自定义 ...
- 单例模式的Java泛型实现方式
import java.util.HashMap; import java.util.Map; /** * Created by zhao.wu on 2016/11/18. */ public cl ...
- PHPExcel 导出图片
$objDrawing = new PHPExcel_Worksheet_Drawing(); // 本地图片文件路径 $objDrawing->setPath('/www/images/img ...
- Jekyll本地搭建开发环境以及Github部署流程
转载自: http://www.jianshu.com/p/f37a96f83d51 前言 博客从wordpres迁移到Jekyll上来了,整个过程还是很顺利的.Jekyll是什么?它是一个简单静态博 ...
- package.json中的script选项作用
npm不仅可以用于模块管理,还可以用于执行脚本.package.json文件有一个scripts字段,可以用于指定脚本命令,供npm直接调用. 接下来做个简单测试: (1)在项目根目录下创建demo. ...
- 「BJWC2010」模板严格次小生成树
题目描述 小 \(C\) 最近学了很多最小生成树的算法,\(Prim\) 算法.\(Kruskal\) 算法.消圈算法等等.正当小\(C\)洋洋得意之时,小\(P\)又来泼小\(C\)冷水了.小\(P ...
- Dism++ 更新管理提示“无法连接服务器”
Dism++ 更新管理提示"无法连接服务器" 下载wsusscn3.cab,放入Dism++安装目录下Config文件夹中.
- spring 参数校验
1.了解下资源文件加载 MessageSource 需要国际化处理时使用这个类 (在需要处理国际化的地方使用messageSource.getMessage(this.getResponseCod ...