博客园  :: 首页  :: 新随笔  :: 订阅 订阅  :: 管理

PHP PDO小试

Posted on 2013-02-26 21:38  PHP-张工  阅读(674)  评论(0编辑  收藏  举报

网上关于PDO的资料很多。这里就不累赘了。

这里我将PDO所有操作封装到一个类里方便操作。

类代码如下:

class DB {
	
	//pdo对象
	public $con = NULL;
	
	function DB()
	{
		$this->con = new PDO("mysql:host=127.0.0.1;dbname=dbtest", "root", "xxx", array(
			PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES `utf8`',
			PDO::ATTR_PERSISTENT => TRUE,
		));
		
		$this->con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		$this->con->setAttribute(PDO::ATTR_CASE, PDO::CASE_UPPER);
	}
	
	public function query($sql, $para = NULL)
	{
		$sqlType = strtoupper(substr($sql, 0, 6));
		
		$cmd = $this->con->prepare($sql);
		if($para != NULL)
		{
			$cmd->execute($para);
		}
		else
		{
			$cmd->execute();
		}
		
		if($sqlType == "SELECT")
		{
			return $cmd->fetchAll();	
		}
		
		if($sqlType == "INSERT")
		{
			return $this->con->lastInsertId();
		}
		
		return $cmd->rowCount();
	}
}

使用方法:

include "pdo.php";

$db = new DB();
$subjectList = $db->query("SELECT * FROM `table1`");
$count = $db->query("UPDATE `table1` SET `name` = 'test' WHERE `id` = :id", array(':id' => 795));

try
{
	echo $db->con->beginTransaction();
	$count = $db->con->exec("UPDATE `table1` SET `name` = 'test1' WHERE `id` = 795");
	$count = $db->con->exec("UPDATE `table1` SET `name1` = 'test22' WHERE `id` = 795");
	$count = $db->con->exec("UPDATE `table1` SET `name1` = 'test333' WHERE `id` = 795");
	echo $db->con->commit();
}
catch (Exception $e)
{
	// MYSQL 的表类型 InnoDB(支持事务) MyISAM(不支持事务)
	echo $db->con->rollBack();
	throw new MyException("事务测试错误", $e);
}

$db = NULL;

PDO支持SQL语句以参数方式调用,可有效的防止SQL注入。