封装了一个PDO的类,希望CSDN的大牛们指导一下不足之处
封装了一个PDO的类,希望CSDN的大牛们指点一下不足之处 封装了一个PDO的类,希望CSDN的大牛们指点一下不足之处。 大师们,comeon! ?php /** *PDO封装类,目的是为了使用起来更简单方便 *modifyDate:2014-07-01 */ classPDOX{ private$pdo=null; public$statem
封装了一个PDO的类,希望CSDN的大牛们指点一下不足之处
封装了一个PDO的类,希望CSDN的大牛们指点一下不足之处。
大师们,come on !
<?php<br /> /**<br /> * PDO封装类,目的是为了使用起来更简单方便<br /> * modify Date: 2014-07-01<br /> */<br /> class PDOX {<br /> private $pdo = null;<br /> <br /> public $statement = null;<br /> <br /> public $options = array(<br /> PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES ",<br /> );<br /> <br /> public function __construct($dsn, $user = '', $pass = '', $persistent = false, $charset = "utf8"){<br /> $this->options[PDO::MYSQL_ATTR_INIT_COMMAND] .= $charset;<br /> if($persistent){<br /> $this->options[PDO::ATTR_PERSISTENT] = true;<br /> }<br /> $this->pdo = new PDO($dsn, $user, $pass, $this->options);<br /> }<br /> /**<br /> 全局属性设置,包括:列名格式和错误提示类型 可以使用数字也能直接使用参数<br /> */<br /> public function setAttr($param, $val = ''){<br /> if(is_array($param)){<br /> foreach($param as $key => $val){<br /> $this->pdo->setAttribute($key, $val);<br /> }<br /> }else{<br /> if($val != '' ){<br /> $this->pdo->setAttribute($param, $val);<br /> }else{<br /> return false;<br /> }<br /> }<br /> }<br /> /**<br /> 生成一个编译好的sql语句模版 你可以使用 ? :name 的形式<br /> 返回一个statement对象<br /> */<br /> public function prepare($sql){<br /> if(empty($sql)){<br /> return false;<br /> }<br /> $this->statement = $this->pdo->prepare($sql);<br /> return $this->statement;<br /> }<br /> /**<br /> 执行Sql语句,一般用于 增、删、更新或者设置 返回影响的行数<br /> */<br /> public function exec($sql){<br /> if(empty($sql)){<br /> return false;<br /> }<br /> try{<br /> return $this->pdo->exec($sql);<br /> }catch(Exception $e){<br /> return $e->getMessage();<br /> }<br /> }<br /> /**<br /> 执行有返回值的查询,返回PDOStatement 可以通过链式操作,可以通过这个类封装的操作获取数据<br /> */<br /> public function query($sql){<br /> if(empty($sql)){<br /> return false;<br /> }<br /> $this->statement = $this->pdo->query($sql);<br /> return $this->statement;<br /> }<br /> /**<br /> 开启事务<br /> */<br /> public function beginTransaction(){<br /> return $this->pdo->beginTransaction();<br /> }<br /> /**<br /> 提交事务<br /> */<br /> public function commit(){<br /> return $this->pdo->commit();<br /> }<br /> /**<br /> 事务回滚<br /> */<br /> public function rollBack(){<br /> return $this->pdo->rollBack();<br /> }<br /> <br /> public function lastInertId(){<br /> return $this->pdo->lastInsertId();<br /> }<br /> <br /> <br /> //** PDOStatement 类操作封装 **//<br /> <br /> /**<br /> 让模版执行SQL语句,1、执行编译好的 2、在执行时编译<br /> */<br /> public function execute($param = ""){<br /> if(is_array($param)){<br /> try{<br /> return $this->statement->execute($param);<br /> }catch (Exception $e){<br /> //return $this->errorInfo();<br /> return $e->getMessage();<br /> }<br /> }else{<br /> try{<br /> return $this->statement->execute();<br /> }catch(Exception $e){<br /> /* 返回的错误信息格式<br /> [0] => 42S22<br /> [1] => 1054<br /> [2] => Unknown column 'col' in 'field list'<br /> return $this->errorInfo();<br /> */<br /> return $e->getMessage();<br /> }<br /> }<br /> }<br /> <br /> /**<br /> 参数1说明:<br /> PDO::FETCH_BOTH 也是默认的,两者都有(索引,关联)<br /> PDO::FETCH_ASSOC 关联数组<br /> PDO::FETCH_NUM 索引<br /> PDO::FETCH_OBJ 对象<br /> PDO::FETCH_LAZY 对象 会附带queryString查询SQL语句<br /> PDO::FETCH_BOUND 如果设置了bindColumn,则使用该参数<br /> */<br /> public function fetch($fetch_type = PDO::FETCH_ASSOC){<br /> if(is_object($this->statement)){<br /> return $this->statement->fetch($fetch_type);<br /> }<br /> return false;<br /> }<br /> /**<br /> 参数1说明:<br /> PDO::FETCH_BOTH 也是默认的,两者都有(索引,关联)<br /> PDO::FETCH_ASSOC 关联数组<br /> PDO::FETCH_NUM 索引<br /> PDO::FETCH_OBJ 对象<br /> PDO::FETCH_COLUMN 指定列 参数2可以指定要获取的列<br /> PDO::FETCH_CLASS 指定自己定义的类<br /> PDO::FETCH_FUNC 自定义类 处理返回的数据<br /> PDO_FETCH_BOUND 如果你需要设置bindColumn,则使用该参数<br /> 参数2说明:<br /> 给定要处理这个结果的类或函数<br /> */<br /> public function fetchAll($fetch_type = PDO::FETCH_ASSOC, $handle = ''){<br /> if(empty($handle)){<br /> return $this->statement->fetchAll($fetch_type);<br /> }<br /> return $this->statement->fetchAll($fetch_type, $handle);<br /> }<br /> /**<br /> 以对象形式返回 结果 跟fetch(PDO::FETCH_OBJ)一样<br /> */<br /> public function fetchObject($class_name){<br /> if(empty($clss_name)){<br /> return $this->statement->fetchObject();<br /> }<br /> return $this->statement->fetchObject($class_name);<br /> }<br /> <br /> public function fetchColumn($intColumn = 0){<br /> return $this->statement->fetchColumn($intColumn);<br /> }<br /> <br /> /**<br /> public function bindColumn($array=array(),$type=EXTR_OVERWRITE){<br /> if(count($array)>0){<br /> extract($array,$type);<br /> }<br /> //$this->statement->bindColumn()<br /> }<br /> */<br /> <br /> /**<br /> 以引用的方式绑定变量到占位符(可以只执行一次prepare,执行多次bindParam达到重复使用的效果)<br /> */<br /> public function bindParam($parameter, $variable, $data_type = 'STR', $length = 0){<br /> switch ($data_type){<br /> case 'STR':<br /> $data_type = PDO::PARAM_STR;<br /> break;<br /> case 'INT':<br /> $data_type = PDO::PARAM_INT;<br /> break;<br /> default :<br /> $data_type = '';<br /> 【本文来自鸿网互联 (http://www.68idc.cn)】 break;<br /> }<br /> return $this->statement->bindParam($parameter, $variable, $data_type, $length);<br /> }<br /> <br /> /**<br /> 返回statement记录集的行数<br /> */<br /> public function rowCount(){<br /> return $this->statement->rowCount();<br /> }<br /> public function count(){<br /> return $this->statement->rowCount();<br /> }<br /> public function columnCount(){<br /> $this->statement->execute();<br /> return $this->statement->columnCount();<br /> }<br /> public function getColumnMeta($intColumn){<br /> return $this->statement->getColumnMeta($intColumn);<br /> }<br /> <br /> <br /> /**<br /> 关闭<br /> */<br /> public function close(){<br /> return $this->statement->closeCursor();<br /> }<br /> <br /> public function closeCursor(){<br /> return $this->statement->closeCursor();<br /> }<br /> /**<br /> 返回错误信息也包括错误号<br /> */<br /> private function errorInfo(){<br /> return $this->statement->errorInfo();<br /> }<br /> /**<br /> 返回错误号<br /> */<br /> private function errorCode(){<br /> return $this->statement->errorCode();<br /> }<br /> <br /> <br /> <br /> //简化操作<br /> public function insert($table, $data){<br /> if(!is_array($data)){<br /> return false;<br /> }<br /> $cols = array();<br /> $vals = array();<br /> foreach($data as $key => $val){<br /> $cols[] = $key;<br /> $vals[] = "'" . $val . "'";<br /> }<br /> $sql = "INSERT INTO {$table} (";<br /> $sql .= implode(",", $cols) . ") VALUES ("; <br /> $sql .= implode(",", $vals) . ")";<br /> return $this->exec($sql);<br /> }<br /> public function insertBind($table, $arrayData){<br /> if(!is_array($arrayData)){<br /> return false;<br /> }<br /> $vals = array_keys($arrayData);<br /> $cols = array();<br /> /*<br /> $arrayobject = new ArrayObject( $arrayData );<br /> $iterator = $arrayobject->getIterator();<br /> while($iterator->valid()) {<br /> $vals[] = ':' . $iterator->key() . '';<br /> $iterator->next();<br /> }<br /> */<br /> $c = implode('', $vals);<br /> $cols = array_filter(explode(':', $c));<br /> <br /> $sql = "INSERT INTO {$table} (";<br /> $sql .= implode(",", $cols) . ") VALUES ("; <br /> $sql .= implode(",", $vals) . ")";<br /> <br /> $this->statement = $this->pdo->prepare($sql);<br /> $this->statement->execute($arrayData);<br /> return $this->statement->rowCount();<br /> }<br /> <br /> public function update($table, $data, $where){<br /> if(!is_array($data)){<br /> return false;<br /> }<br /> $set = array();<br /> foreach($data as $key => $val){<br /> $set[] = $key . "='" . $val . "'";<br /> }<br /> $sql = "UPDATE {$table} SET ";<br /> $sql .= implode(",", $set);<br /> $sql .= " WHERE " . $where;<br /> return $this->exec($sql);<br /> }<br /> public function updateBind($sql, $arrayWhere){<br /> if(empty($sql) || !is_array($arrayWhere)){<br /> return false;<br /> }<br /> $this->statement = $this->pdo->prepare($sql);<br /> $this->statement->execute($arrayWhere);<br /> return $this->statement->rowCount();<br /> }<br /> <br /> <br /> public function delete($table, $where){<br /> if(empty($table) || empty($where)){<br /> return false;<br /> } <br /> $sql = "DELETE FROM {$table} WHERE " . $where;<br /> return $this->exec($sql);<br /> }<br /> public function deleteBind($sql, $arrayWhere){<br /> if(empty($sql) || !is_array($arrayWhere)){<br /> return false;<br /> }<br /> $this->statement = $this->pdo->prepare($sql);<br /> $this->statement->execute($arrayWhere);<br /> return $this->statement->rowCount();<br /> }<br /> }<br /> ?>
毕竟在一个项目当中,不可能到处的写PDO自身的一些东西。也不要说PDO已经封装好了,无须再次封装之类的废话。
------解决思路----------------------
几点建议:
1、如果我
$db = new PDOX;
$a = $db->query($sql1);
$b = $db->query($sql2);
print_r($a->fetchall());
print_r($b->fetchall());
可以吗?显然是不可以的,因为
$this->statement = $this->pdo->query($sql);
前一次的查询结果被后一次的覆盖了
2、事务(Transaction)操作宜封装成整体,只传入一组 sql 而隐藏相关操作
3、没考虑使用存储过程
4、PDOX 可直接继承于 PDO 而无需抄写 PDO 已有方法

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is a popular web development language that has been used for a long time. The PDO (PHP Data Object) class integrated in PHP is a common way for us to interact with the database during the development of web applications. However, a problem that some PHP developers often encounter is that when using the PDO class to interact with the database, they receive an error like this: PHPFatalerror:CalltoundefinedmethodPDO::prep

As a popular programming language, PHP is widely used in the field of web development. Among them, PHP's PDO_PGSQL extension is a commonly used PHP extension. It provides an interactive interface with the PostgreSQL database and can realize data transmission and interaction between PHP and PostgreSQL. This article will introduce in detail how to use PHP's PDO_PGSQL extension. 1. What is the PDO_PGSQL extension? PDO_PGSQL is an extension library of PHP, which

PHP and PDO: How to perform batch inserts and updates Introduction: When using PHP to write database-related applications, you often encounter situations where you need to batch insert and update data. The traditional approach is to use loops to perform multiple database operations, but this method is inefficient. PHP's PDO (PHPDataObject) provides a more efficient way to perform batch insert and update operations. This article will introduce how to use PDO to implement batch insert and update operations. 1. Introduction to PDO: PDO is PH

PHP and PDO: How to perform a full-text search in a database In modern web applications, the database is a very important component. Full-text search is a very useful feature when we need to search for specific information from large amounts of data. PHP and PDO (PHPDataObjects) provide a simple yet powerful way to perform full-text searches in databases. This article will introduce how to use PHP and PDO to implement full-text search, and provide some sample code to demonstrate the process. first

PHP and PDO: How to handle JSON data in databases In modern web development, processing and storing large amounts of data is a very important task. With the popularity of mobile applications and cloud computing, more and more data are stored in databases in JSON (JavaScript Object Notation) format. As a commonly used server-side language, PHP's PDO (PHPDataObject) extension provides a convenient way to process and operate databases. Book

PHP and PDO: How to query and display data in pages When developing web applications, querying and displaying data in pages is a very common requirement. Through paging, we can display a certain amount of data at a time, improving page loading speed and user experience. In PHP, the functions of paging query and display of data can be easily realized using the PHP Data Object (PDO) library. This article will introduce how to use PDO in PHP to query and display data by page, and provide corresponding code examples. 1. Create database and data tables

PDOPDO is an object-oriented database access abstraction layer that provides a unified interface for PHP, allowing you to use the same code to interact with different databases (such as Mysql, postgresql, oracle). PDO hides the complexity of underlying database connections and simplifies database operations. Advantages and Disadvantages Advantages: Unified interface, supports multiple databases, simplifies database operations, reduces development difficulty, provides prepared statements, improves security, supports transaction processing Disadvantages: performance may be slightly lower than native extensions, relies on external libraries, may increase overhead, demo code uses PDO Connect to mysql database: $db=newPDO("mysql:host=localhost;dbnam

1. Introduction to PDO PDO is an extension library of PHP, which provides an object-oriented way to operate the database. PDO supports a variety of databases, including Mysql, postgresql, oracle, SQLServer, etc. PDO enables developers to use a unified API to operate different databases, which allows developers to easily switch between different databases. 2. PDO connects to the database. To use PDO to connect to the database, you first need to create a PDO object. The constructor of the PDO object receives three parameters: database type, host name, database username and password. For example, the following code creates an object that connects to a mysql database: $dsn="mysq
