Table of Contents
回复讨论(解决方案)
Home Backend Development PHP Tutorial 封装了一个PDO的类,希望CSDN的大牛们指点一下不足之处

封装了一个PDO的类,希望CSDN的大牛们指点一下不足之处

Jun 23, 2016 pm 01:26 PM

封装了一个PDO的类,希望CSDN的大牛们指点一下不足之处。

大师们,come on !

<?php/** * PDO封装类,目的是为了使用起来更简单方便 * modify Date: 2014-07-01 */class PDOX {	private $pdo 	   = null;		public  $statement = null;		public  $options = array(		PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES ",	);		public function __construct($dsn, $user = '', $pass = '', $persistent = false, $charset = "utf8"){		$this->options[PDO::MYSQL_ATTR_INIT_COMMAND] .= $charset;		if($persistent){			$this->options[PDO::ATTR_PERSISTENT] = true;		}		$this->pdo = new PDO($dsn, $user, $pass, $this->options);	}	/**	全局属性设置,包括:列名格式和错误提示类型    可以使用数字也能直接使用参数	*/	public function setAttr($param, $val = ''){		if(is_array($param)){			foreach($param as $key => $val){				$this->pdo->setAttribute($key, $val);			}		}else{			if($val != '' ){				$this->pdo->setAttribute($param, $val);			}else{				return false;			}		}	}	/**	生成一个编译好的sql语句模版 你可以使用 ? :name 的形式	返回一个statement对象	*/	public function prepare($sql){		if(empty($sql)){			return false;		}		$this->statement = $this->pdo->prepare($sql);		return $this->statement;	}	/**	执行Sql语句,一般用于 增、删、更新或者设置  返回影响的行数	*/	public function exec($sql){		if(empty($sql)){			return false;		}		try{			return $this->pdo->exec($sql);		}catch(Exception $e){			return $e->getMessage();		}	}	/**	执行有返回值的查询,返回PDOStatement  可以通过链式操作,可以通过这个类封装的操作获取数据	*/	public function query($sql){		if(empty($sql)){			return false;		}		$this->statement = $this->pdo->query($sql);		return $this->statement;	}	/**	开启事务	*/	public function beginTransaction(){		return $this->pdo->beginTransaction();	}	/**	提交事务	*/	public function commit(){		return $this->pdo->commit();	}	/**	事务回滚	*/	public function rollBack(){		return $this->pdo->rollBack();	}		public function lastInertId(){		return $this->pdo->lastInsertId();	}			//**   PDOStatement 类操作封装    **//		/**	让模版执行SQL语句,1、执行编译好的 2、在执行时编译	*/	public function execute($param = ""){		if(is_array($param)){			try{				return $this->statement->execute($param);			}catch (Exception $e){				//return $this->errorInfo();				return $e->getMessage();			}		}else{			try{				return $this->statement->execute();			}catch(Exception $e){				/* 返回的错误信息格式				[0] => 42S22    			[1] => 1054    			[2] => Unknown column 'col' in 'field list'    			return $this->errorInfo();    			*/				return $e->getMessage();			}		}	}		/**	参数1说明:	PDO::FETCH_BOTH		也是默认的,两者都有(索引,关联)	PDO::FETCH_ASSOC	关联数组	PDO::FETCH_NUM		索引	PDO::FETCH_OBJ			对象	PDO::FETCH_LAZY		对象 会附带queryString查询SQL语句	PDO::FETCH_BOUND	如果设置了bindColumn,则使用该参数	*/	public function fetch($fetch_type = PDO::FETCH_ASSOC){		if(is_object($this->statement)){			return $this->statement->fetch($fetch_type);		}		return false;	}	/**	参数1说明:	PDO::FETCH_BOTH		也是默认的,两者都有(索引,关联)	PDO::FETCH_ASSOC	关联数组	PDO::FETCH_NUM		索引	PDO::FETCH_OBJ		对象	PDO::FETCH_COLUMN	指定列 参数2可以指定要获取的列	PDO::FETCH_CLASS	指定自己定义的类	PDO::FETCH_FUNC		自定义类 处理返回的数据	PDO_FETCH_BOUND	如果你需要设置bindColumn,则使用该参数	参数2说明:	给定要处理这个结果的类或函数	*/	public function fetchAll($fetch_type = PDO::FETCH_ASSOC, $handle = ''){		if(empty($handle)){			return $this->statement->fetchAll($fetch_type);		}		return $this->statement->fetchAll($fetch_type, $handle);	}	/**	以对象形式返回 结果 跟fetch(PDO::FETCH_OBJ)一样	*/	public function fetchObject($class_name){		if(empty($clss_name)){			return $this->statement->fetchObject();		}		return $this->statement->fetchObject($class_name);	}		public function fetchColumn($intColumn = 0){		return $this->statement->fetchColumn($intColumn);	}		/**	public function bindColumn($array=array(),$type=EXTR_OVERWRITE){		if(count($array)>0){			extract($array,$type);		}		//$this->statement->bindColumn()	}	*/		/**	以引用的方式绑定变量到占位符(可以只执行一次prepare,执行多次bindParam达到重复使用的效果)	*/	public function bindParam($parameter, $variable, $data_type = 'STR', $length = 0){		switch ($data_type){			case  'STR':				$data_type = PDO::PARAM_STR;				break;			case 'INT':				$data_type = PDO::PARAM_INT;				break;			default :				$data_type = '';				break;		}		return $this->statement->bindParam($parameter, $variable, $data_type, $length);	}		/**	返回statement记录集的行数	*/	public function rowCount(){		return $this->statement->rowCount();	}	public function count(){		return $this->statement->rowCount();	}	public function columnCount(){		$this->statement->execute();		return $this->statement->columnCount();	}	public function getColumnMeta($intColumn){		return $this->statement->getColumnMeta($intColumn);	}			/**	关闭	*/	public function close(){		return $this->statement->closeCursor();	}		public function closeCursor(){		return $this->statement->closeCursor();	}	/**	返回错误信息也包括错误号	*/	private function errorInfo(){		return $this->statement->errorInfo();	}	/**	返回错误号	*/	private function errorCode(){		return $this->statement->errorCode();	}				//简化操作	public function insert($table, $data){		if(!is_array($data)){			return false;		}		$cols = array();		$vals = array();		foreach($data as $key => $val){			$cols[] = $key;			$vals[] = "'" . $val . "'";		}		$sql  = "INSERT INTO {$table} (";		$sql .= implode(",", $cols) . ") VALUES (";				$sql .= implode(",", $vals) . ")";		return $this->exec($sql);	}	public function insertBind($table, $arrayData){		if(!is_array($arrayData)){			return false;		}		$vals = array_keys($arrayData);		$cols = array();		/*		$arrayobject  = new  ArrayObject( $arrayData );		$iterator  	  =  $arrayobject->getIterator();		while($iterator->valid()) {			$vals[] =  ':' . $iterator->key() . '';			$iterator->next();		}		*/		$c	  = implode('', $vals);		$cols = array_filter(explode(':', $c));		$sql  = "INSERT INTO {$table} (";		$sql .= implode(",", $cols) . ") VALUES (";				$sql .= implode(",", $vals) . ")";				$this->statement = $this->pdo->prepare($sql);		$this->statement->execute($arrayData);		return  $this->statement->rowCount();	}		public function update($table, $data, $where){		if(!is_array($data)){			return false;		}		$set = array();		foreach($data as $key => $val){			$set[] = $key . "='" . $val  . "'";		}		$sql = "UPDATE {$table} SET ";		$sql .= implode(",", $set);		$sql .= " WHERE " . $where;		return $this->exec($sql);	}	public function updateBind($sql, $arrayWhere){		if(empty($sql) || !is_array($arrayWhere)){			return false;		}		$this->statement = $this->pdo->prepare($sql);		$this->statement->execute($arrayWhere);		return $this->statement->rowCount();	}		public function delete($table, $where){		if(empty($table) || empty($where)){			return false;		} 		$sql = "DELETE FROM {$table} WHERE " . $where;		return $this->exec($sql);	}	public function deleteBind($sql, $arrayWhere){		if(empty($sql) || !is_array($arrayWhere)){			return false;		}		$this->statement = $this->pdo->prepare($sql);		$this->statement->execute($arrayWhere);		return $this->statement->rowCount();	}}?>
Copy after login




毕竟在一个项目当中,不可能到处的写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 已有方法


总的来说还不错,但感觉上有些方法过于细琐,可以有必要的整合在一起

几点建议:
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 已有方法


谢谢你的宝贵意见,我仅仅是想让它操作更简单化一点。
1、像你举的这个例子,可有解决方法。
2、事务我很少用到,也不知道该怎样封装。如果你能指点一下更好。
3、存储过程也很少用到。
4、抄写PDO的方法,只是想在使用上和PDO无异样,方便直接写PDO的朋友直接使用此类。无须过多的学习。不像其它的数据库类,在学完原生的数据库操作后,又要再次学习一个新的数据库操作,可能它很简单,但学习也是要时间的。



总的来说还不错,但感觉上有些方法过于细琐,可以有必要的整合在一起


请问怎样整合会更简洁此呢??

封装的目的是为了简化操作,不常用的就没有不要封装了

class PDOX extends PDO {  //执行各种 sql 指令,并可通过参数 $param 进行扩展  function query($sql, $param=null) {}  //查询并返回单条记录  function fetch($sql) {};  //查询并以数组方式返回多条记录  function fetchall($sql) {}}
Copy after login
Copy after login
数据库类只要有这三个方法就可满足绝大多数应用的需要了
由于是继承于 PDO,所以 PDO 原有的方法一个也不会少

@xuzuning

$db = new PDOX;
$a = $db->query($sql1);
$b = $db->query($sql2);
print_r($a->fetchall());
print_r($b->fetchall());

这种写法的程序员应该不多吧?如果这样的话,可以考虑先放弃这种操作支持。如果我的类在效率或者并发上有问题的话,这才是大问题。

这个类内部是否有错误或者不妥之处??

各位大牛,请多多发言。

嵌套甚至递归的查询在读取分类树时是经常用到的,怎么能说不多呢?
嗯,做个留言板是不需要的

简单的插入数据:
$data = array(':title'=>$title, ':content'=>$content);
$pdo = new PDOX;
$lastID = $pdo->insertBind('article', $data);


修改数据:
$data = array(':title'=>$title, ':id'=>$id);
$sql = 'update article set title=:title where id=:id';
$yesorno = $pdo->updateBind($sql, $data);

删除数据:
$data = array(':id'=>$id);
$sql = 'delete article where id=:id';
$yesorno = $pdo->deleteBind($sql, $data);

最主要的是这种写法,可以省下很多的代码量。这才是我写此类的关键。

嵌套甚至递归的查询在读取分类树时是经常用到的,怎么能说不多呢?
嗯,做个留言板是不需要的



你说的这个还真是,在递归中需要使用。想使用此类的朋友要注意了。

我会尽量优化PHP代码或者使用其它方法替代递归,因为递归有些耗资源。

谢谢你提醒。

表示看的挺纠结的

表示看的挺纠结的



杂纠结了???

我觉得在操作数据时挺方便的呀

大牛们,继续呀。。

封装的目的是为了简化操作,不常用的就没有不要封装了

class PDOX extends PDO {  //执行各种 sql 指令,并可通过参数 $param 进行扩展  function query($sql, $param=null) {}  //查询并返回单条记录  function fetch($sql) {};  //查询并以数组方式返回多条记录  function fetchall($sql) {}}
Copy after login
Copy after login
数据库类只要有这三个方法就可满足绝大多数应用的需要了
由于是继承于 PDO,所以 PDO 原有的方法一个也不会少



不知道版主可有更好的PDO操作类???
可否贡献一个。

不怎么样!
另外预处理部分没有封装

	/**	 * 将数组转换为SQL语句	 * @param array $where 要生成的数组	 * @param string $font 连接串。	 */	final public function sqls($where, $font = ' AND ') {				# 先将bindColumn存起来				$this->bindColumn = array();		if (is_array($where)) {			$sql = '';			foreach ($where as $key=>$val) {				$sql .= $sql ? " $font `$key` = :$key " : " `$key` = :$key";				$this->bindColumn = array($key, $val);			}			return ;		} else {			return $where;		}	}
Copy after login

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1264
29
C# Tutorial
1237
24
Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Apr 08, 2025 am 12:03 AM

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Explain the difference between self::, parent::, and static:: in PHP OOP. Explain the difference between self::, parent::, and static:: in PHP OOP. Apr 09, 2025 am 12:04 AM

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

How does PHP handle file uploads securely? How does PHP handle file uploads securely? Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

See all articles