php操作数据库mysql之pdo类 mySQLHelper2

//mySQLHelper v2.0
class mySQLHelper{
	//-----------------数据库连接信息-----------------//
	//-数据库地址
	private $host	='127.0.0.1';
	//-数据库名
	private $dbname	='xmlink168';
	//-数据库用户名
	private $uid	='root';
	//-数据库密码
	private $pwd	='root';
	//-----------------数据库连接信息-----------------//
	public $con;
	function __construct(){
		try{
			$this->con = new PDO(
				"mysql:host=".$this->host.";dbname=".$this->dbname,
				$this->uid,$this->pwd, 
				array(PDO::MYSQL_ATTR_INIT_COMMAND => "set names 'utf8';")
			);
		}catch(PDOException $e){
			die("Error!");
		}catch(Exception $e){
			die("Connect Error!");
		}
	}
	
	//返回结果集合,失败返回null(select)
	public function MyQuery($sql){
		$data=$this->con->query($sql);
		if($data)
			return $data->fetchAll();
		else
			return null;
	}
	public function GetAll($sql,$arr=array()){
		try{
			$dp=$this->con->prepare($sql);//准备查询语句
			if(is_array($arr)){
				for($i=1;$i<=count($arr);$i++){
					$dp->bindParam($i,$arr[$i-1]);//绑定参数
				}
			}
			$dp->execute();//执行查询语句,并返回结果集
			return $dp->fetchAll();			
		}catch(Exception $e){
			die("Error");
		}
	}
	public function GetOne($sql,$arr=array()){
		try{
			$dp=$this->con->prepare($sql);//准备查询语句
			if(is_array($arr)){
				for($i=1;$i<=count($arr);$i++){
					$dp->bindParam($i,$arr[$i-1]);//绑定参数
				}
			}
			$dp->execute();//执行查询语句,并返回结果集
			return $dp->fetch(PDO::FETCH_ASSOC);
		}catch(Exception $e){
			die("Error");
		}
	}
	
	//Insert 成功返回最新自增字段(ID)
	public function Insert($sql,$arr=array()){
		try{
			$dp=$this->con->prepare($sql);
			if(is_array($arr)){
				for($i=1;$i<=count($arr);$i++){
					$dp->bindParam($i,$arr[$i-1]);
				}
			}
			$dp->execute();
			return $this->con->lastInsertId();
		}catch(Exception $e){
			die("Error");
		}
	}
	//返回受影响行数
	public function Update($sql,$arr=array()){
		try{
			$dp=$this->con->prepare($sql);
			if(is_array($arr)){
				for($i=1;$i<=count($arr);$i++){
					$dp->bindParam($i,$arr[$i-1]);
				}
			}
			return $dp->execute();//exec() 处理一条SQL语句,并返回所影响的条目数
		}catch(Exception $e){
			die("Error");
		}
	}
	
	//返回受影响行数(delete,update)
	public function Excute($sql){
		try{
			$rows=$this->con->exec($sql);
			return $rows;
		}catch(Exception $e){
			die("Error");
		}
	}
	
	//满足条件数量统计(select count(*) ... )
	public function RowsCount($sql,$arr=array()){
		try{
			/*
			$data=$this->con->query($sql);
			return $data->fetchColumn();
			*/
			$dp=$this->con->prepare($sql);		
			if(is_array($arr)){
				for($i=1;$i<=count($arr);$i++){
					$dp->bindParam($i,$arr[$i-1]);
				}
			}
			$dp->execute();
			if($dp){
				$x = $dp->fetchColumn();
				return intval($x);
			}
			return 0;
		}catch(Exception $e){
			die("Error");
		}
	}
}

InnoDB事务支持:

1、关闭 PDO 的自动提交;

$pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, false);

2、开启一个事务需要的方法;

$pdo->beginTransaction(); // 开启一个事务
$pdo->commit(); // 提交事务
$pdo->rollback(); // 回滚事务