0

0

PDO链式调用的封装类

PHP中文网

PHP中文网

发布时间:2016-05-23 16:38:35

|

1429人浏览过

|

来源于php中文网

原创

                       

1. [代码][PHP]代码   

           

 '127.0.0.1',
		'username' => 'root',
		'password' => '',
		'database' => 'test',
		'charset' => 'utf8',
		'prefix' => '',
		'persistent' => false,
		'debug'=>true
));

//多行插入
$db->Insert( 't', array (
		array (
				'cid' => $cid,
				'content' => "c1" 
		),
		array (
				'cid' => $cid,
				'content' => "c2" 
		) 
) )
->Execute();

//单行插入并获取id
$id = $db->Insert( 't', array (
		'cid' => $cid,
		'content' => $content
) )
->LastId();

//查询1:最简查询
$result = $db->Select( 't' )->FetchAll();

//查询2:带条件查询
$result = $db->Select( 't', array (	'id', 'cid', 'content') )
->Where( 'cid=? and id>?', array ($cid, $id) )
->Order( 'id desc' )
->Limit( 1 )
->FetchRow();

//查询3:in用法
$where_data[] = $cid;
$ids = array(1,2,3);
$where_data += $ids;
$result = $db->Select( 't' )
->Where( 'cid=? and id in(?)', $where_data )
->FetchAll();

//更新
$count = $db->Update( 't', array (
		'id' => $id,
		'cid' => $cid,
		'content' => $content
) )
->Where( 'id=?', $id )
->AffectedRows();

//删除
$count = $db->Delete( 't' )->Where( 'id=?', $id )->AffectedRows();

//sql语句查询
$result = $db->Sql( 'select * from `_t` where id>?', $id )->FetchAll();

//通过自定义来使用事务
$pdo = $db->GetConnecttion();
$pdo->beginTransaction();
...

*/
class PDOHelper
{
	protected $mConnecttion;
	protected $mPrefix;
	protected $mDebug;
	protected $mQueryType;
	protected $mSql;
	protected $mWhere;
	protected $mOrder;
	protected $mLimit;
	protected $mData;
	protected $mPDOStatement;
	/**
	 * 构造方法
	 * 
	 * @param array $config        	
	 */
	function __construct($config)
	{
		$this->mDebug = empty( $config['debug'] ) ? false : true;
		$this->mPrefix = isset( $config['prefix'] ) ? $config['prefix'] : '';
		$dsn = 'mysql:host=' . $config['host'] . ';dbname=' . $config['database'];
		try
		{
			$this->mConnecttion = new PDO( $dsn, $config['username'], $config['password'], array (
					PDO::ATTR_PERSISTENT => empty( $config['persistent'] ) ? false : true 
			) );
		}
		catch ( PDOException $e )
		{
			$this->Err( 'Connect failed
' ); } if ($this->mConnecttion) { // $this->mConnecttion->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); $this->mConnecttion->setAttribute( PDO::ATTR_EMULATE_PREPARES, false ); $this->mConnecttion->setAttribute( PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC ); $charset = isset( $config['charset'] ) ? $config['charset'] : 'utf8'; // $charset = strtolower( str_replace( '-', '', $charset ) ); // if (! in_array( $charset, array ('utf8','gbk') )) // { // $charset = 'utf8'; // } $this->mConnecttion->exec( "SET NAMES $charset" ); } } /** * 获取PDO实例,以便自己实现复杂查询 * * @return PDO */ function GetConnecttion() { return $this->mConnecttion; } /** * 初始化链式调用的缓存 */ private function Init() { $this->mQueryType = ''; $this->mSql = ''; $this->mWhere = ''; $this->mOrder = ''; $this->mLimit = ''; $this->mData = array (); } /** * 查询链Select部分 * * @param string $talbe * @param string|array $field * @return PDOHelper */ function Select($talbe, $field = '*') { $this->Init(); $this->mQueryType = 's'; $field_str = is_array( $field ) ? '`' . implode( '`,`', $field ) . '`' : $field; $this->mSql = 'SELECT ' . $field_str . ' FROM `' . $this->mPrefix . $talbe . '`'; return $this; } /** * 查询链Insert部分 * * @param string $talbe * @param array $data * @return PDOHelper */ function Insert($talbe, $data) { $this->Init(); $first = current( $data ); if (is_array( $first )) { // 多行插入 $fields = array_keys( $first ); $values = substr( str_repeat( '?,', count( $fields ) ), 0, - 1 ); $values_all = substr( str_repeat( '(' . $values . '),', count( $data ) ), 0, - 1 ); $this->mSql = 'INSERT INTO `' . $this->mPrefix . $talbe . '`(`' . implode( '`,`', $fields ) . '`) VALUES' . $values_all; foreach ( $this->mData as $item ) { $this->mData += $item; } } else { // 单行插入 $fields = array_keys( $data ); $values = substr( str_repeat( '?,', count( $fields ) ), 0, - 1 ); $this->mSql = 'INSERT INTO `' . $this->mPrefix . $talbe . '`(`' . implode( '`,`', $fields ) . '`) VALUES(' . $values . ')'; $this->mData = $data; } return $this; } /** * 查询链Update部分 * * @param string $talbe * @param array $data * @return PDOHelper */ function Update($talbe, $data) { $this->Init(); $this->mQueryType = 'u'; $fields = array_keys( $data ); $this->mSql = 'UPDATE `' . $this->mPrefix . $talbe . '` SET ' . implode( '=?,', $fields ) . '=?'; $this->mData = $data; return $this; } /** * 查询链Delete部分 * * @param string $talbe * @return PDOHelper */ function Delete($talbe) { $this->Init(); $this->mQueryType = 'd'; $this->mSql = 'DELETE FROM `' . $this->mPrefix . $talbe . '`'; return $this; } /** * 查询链Where部分 * * @param string $str * @param mixed $parameter * @return PDOHelper */ function Where($str, $parameter = null) { if ($parameter !== null) { if (is_array( $parameter )) { $this->mData += $parameter; // 根据实际传递的参数数目,替换in语句中的?,只能有一个in语句 $c1 = substr_count( $str, '?' ); $c2 = count( $parameter ); $replace = 'in(' . substr( str_repeat( '?,', $c2 - $c1 + 1 ), 0, - 1 ) . ')'; $str = str_replace( 'in(?)', $replace, $str ); } else { $this->mData[] = $parameter; } } $this->mWhere = " WHERE $str"; return $this; } /** * 查询链Order部分 * * @param string $str * @return PDOHelper */ function Order($str) { $this->mOrder = " ORDER BY $str"; return $this; } /** * 查询链Limit部分 * * @param number $length * @param number $begin * @return PDOHelper */ function Limit($length = 10, $begin = 0) { $this->mLimit = " LIMIT $begin,$length"; return $this; } /** * 直接Sql语句查询 * * @param string $sql * @param mixed $parameter * @return PDOHelper */ function Sql($sql, $parameter = null) { $this->Init(); if ($parameter !== null) { if (is_array( $parameter )) { $this->mData = $parameter; // 根据实际传递的参数数目,替换in语句中的?,只能有一个in语句 $c1 = substr_count( $sql, '?' ); $c2 = count( $parameter ); $replace = 'in(' . substr( str_repeat( '?,', $c2 - $c1 + 1 ), 0, - 1 ) . ')'; $sql = str_replace( 'in(?)', $replace, $sql ); } else { $this->mData[] = $parameter; } } // 自动为表名加前缀,需要时,请在表名前面加下划线并用反单引号括起来 $sql = str_replace( '`_', '`' . $this->mPrefix, $sql ); $this->mSql = $sql; return $this; } /** * 执行查询 * * @return boolean */ function Execute() { if ($this->mConnecttion) { switch ($this->mQueryType) { case 's' : $this->mSql .= $this->mWhere . $this->mOrder . $this->mLimit; break; case 'u' : $this->mSql .= $this->mWhere; break; case 'd' : $this->mSql .= $this->mWhere; break; } //var_dump( $this->mSql ); //echo '
'; if (empty( $this->mSql )) { $this->Err( 'Can not find SQL statement
' ); return false; } if ($this->mPDOStatement = $this->mConnecttion->prepare( $this->mSql )) { $i = 1; foreach ( $this->mData as $data ) { // echo "<<$i:$data>>
"; if (! $this->mPDOStatement->bindValue( $i, $data )) { $this->Err( 'Error: PDOStatement::bindValue() ' . $i . '/' . count( $this->mData ) . '
' ); return false; } ++ $i; } if ($this->mPDOStatement->execute()) { return true; } $this->Err( 'Error: PDOStatement::execute()
' ); return false; } $this->Err( 'Error: PDOStatement::prepare()
' ); } return false; } /** * 返回数据列表的二维关联数组 * * @return array(array{}) | empty array | false */ function FetchAll() { if ($this->Execute()) { return $this->mPDOStatement->fetchAll(); } else { return false; } } /** * 返回数据行的一维关联数组 * * @return array{} | empty array | false */ function FetchRow() { if ($this->Execute()) { $rs = $this->mPDOStatement->fetch(); return $rs === false ? array () : $rs; } else { return false; } } /** * 返回第1行第1列的值 * * @return mixed | false */ function FetchCell() { if ($this->Execute()) { $rs = $this->mPDOStatement->fetchColumn(); return $rs === false ? null : $rs; } else { return false; } } /** * 返回插入数据的id * * @return string boolean */ function LastId() { if ($this->Execute()) { return $this->mConnecttion->lastInsertId(); } else { return false; } } /** * 返回实际受影响的行数 * * @return number boolean */ function AffectedRows() { if ($this->Execute()) { return $this->mPDOStatement->rowCount(); } else { return false; } } /** * 调试模式下,显示错误信息 * * @param string $msg */ private function Err($msg) { if ($this->mDebug) { echo $msg; } } }

2. [代码]更新说明        

/*
1. 增加对多行插入的支持
2. 增加in语句参数的自动替换
3. 增加注释以及调试模式下的提示信息
4. Submit方法改名为Execute
5. 内部语法结构优化
 */

                   

SuperCms在线订餐系统
SuperCms在线订餐系统

模板采用响应式设计,自动适应手机,电脑及平板显示;满足单一店铺外卖需求。功能:1.菜单分类管理2.菜品管理:菜品增加,删除,修改3.订单管理4.友情链接管理5.数据库备份6.文章模块:如:促销活动,帮助中心7.单页模块:如:企业信息,关于我们更强大的功能在开发中……安装方法:上传到网站根目录,运行http://www.***.com/install 自动

下载

                   

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
php源码安装教程大全
php源码安装教程大全

本专题整合了php源码安装教程,阅读专题下面的文章了解更多详细内容。

7

2025.12.31

php网站源码教程大全
php网站源码教程大全

本专题整合了php网站源码相关教程,阅读专题下面的文章了解更多详细内容。

4

2025.12.31

视频文件格式
视频文件格式

本专题整合了视频文件格式相关内容,阅读专题下面的文章了解更多详细内容。

7

2025.12.31

不受国内限制的浏览器大全
不受国内限制的浏览器大全

想找真正自由、无限制的上网体验?本合集精选2025年最开放、隐私强、访问无阻的浏览器App,涵盖Tor、Brave、Via、X浏览器、Mullvad等高自由度工具。支持自定义搜索引擎、广告拦截、隐身模式及全球网站无障碍访问,部分更具备防追踪、去谷歌化、双内核切换等高级功能。无论日常浏览、隐私保护还是突破地域限制,总有一款适合你!

7

2025.12.31

出现404解决方法大全
出现404解决方法大全

本专题整合了404错误解决方法大全,阅读专题下面的文章了解更多详细内容。

42

2025.12.31

html5怎么播放视频
html5怎么播放视频

想让网页流畅播放视频?本合集详解HTML5视频播放核心方法!涵盖<video>标签基础用法、多格式兼容(MP4/WebM/OGV)、自定义播放控件、响应式适配及常见浏览器兼容问题解决方案。无需插件,纯前端实现高清视频嵌入,助你快速打造现代化网页视频体验。

4

2025.12.31

关闭win10系统自动更新教程大全
关闭win10系统自动更新教程大全

本专题整合了关闭win10系统自动更新教程大全,阅读专题下面的文章了解更多详细内容。

3

2025.12.31

阻止电脑自动安装软件教程
阻止电脑自动安装软件教程

本专题整合了阻止电脑自动安装软件教程,阅读专题下面的文章了解更多详细教程。

3

2025.12.31

html5怎么使用
html5怎么使用

想快速上手HTML5开发?本合集为你整理最实用的HTML5使用指南!涵盖HTML5基础语法、主流框架(如Bootstrap、Vue、React)集成方法,以及无需安装、直接在线编辑运行的平台推荐(如CodePen、JSFiddle)。无论你是新手还是进阶开发者,都能轻松掌握HTML5网页制作、响应式布局与交互功能开发,零配置开启高效前端编程之旅!

2

2025.12.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
php初学者入门课程
php初学者入门课程

共10课时 | 0.6万人学习

Django DRF 源码解析
Django DRF 源码解析

共21课时 | 1.4万人学习

JavaScript OOP调试技巧视频教程
JavaScript OOP调试技巧视频教程

共5课时 | 0.9万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号