dsn = isset($arr['dsn'])?$arr['dsn']:'mysql:host=localhost;dbname=project;';
$this->user = isset($arr['user'])?$arr['user']:'root';
$this->password = isset($arr['password'])?$arr['password']:'759114';
$this->pdo= new PDO($this->dsn,$this->user,$this->password); #实例化pdo对象
}
//利用PDO实现数据库操作
/*
@param string $sql 对sql语句进行判定
*/
private function _Exec($sql){
try{ #进行错误处理
$res = $this->pdo->exec($sql);
if(!$res){ #语句错误,抛出异常
throw new PDOException('出错啦!');
}else{
return $res;
}
}
catch(PDOException $e){
echo $e->getMessage(); #输出异常信息
echo ""; echo "错误所在行:".$e->getLine()."
"; echo "错误编号:".$this->pdo->errorInfo()[1]."
"; echo "错误信息:".$this->pdo->errorInfo()[2]."
"; exit(); } } // 进行插入操作 /* * @param string $sql *@return int 受影响行数 */ public function db_insert($sql){ $res = $this->_Exec($sql); #执行操作 return $this->pdo->lastInsertId(); } // 进行插入操作 /* * @param string $sql *@return int 受影响行数 */ public function db_delete($sql){ $affected = $this->_Exec($sql); #执行操作 return $affected; } //进行更新操作 /* @param string $sql 要插入的sql语句 @retutn int 受影响的行数 */ public function db_update($sql){ $affected = $this->_Exec($sql); #执行操作 return $affected; #返回受影响的行数 } // 判断查询语句的语法是否正确 private function Iserror($sql){ try{ //执行语句 $res = $this->pdo->query($sql); if(!$res){ #语句错误,抛出异常 throw new PDOException('出错啦!'); } return $res; //语句正确 }catch(PDOException $e){ echo $e->getMessage(); #输出错误信息 echo "
"; echo "错误所在行:".$e->getLine()."
"; echo "错误编号:".$this->pdo->errorInfo()[1]."
"; echo "错误信息:".$this->pdo->errorInfo()[2]."
"; exit(); } } //进行获取操作 /* @param string $sql @return array 返回一个数组 */ public function db_getOne($sql){ $stmt = $this->Iserror($sql); #执行sql 语句进行查询, 与exec 方法不同 $row = $stmt->fetch(PDO::FETCH_ASSOC); #返回一个关联数组 return $row; } #获取多行数据 /* @param string $sql 要执行的语句 @return array 返回一个数组 */ public function db_getAll($sql){ $stmt = $this->Iserror($sql); $rows =$stmt->fetchAll($stmt,PDO::FETCH_ASSOC); return $rows; } //pdo 事务处理 /* Tran_start 开启事务 @param string $sp 保存点,默认是sp1 @return boolean */ public function db_tran_start($sp='sp1'){ #执行语句,开启事务 $res = $this->pdo->beginTransaction(); return true; } /* 事务提交 @return boolean */ public function db_tran_commit(){ $this->pdo->commit(); } //事务回滚 public function db_tran_rollback(){ $this->rollBack(); } //预编译处理 /* @param string $sql #sql 语句中使用 ? 作为占位符 @param array $params @param array $arr */ public function db_prepare($sql ,$params ){ #prepare的 预编译语句不需要 Iserror判断 $stmt = $this->pdo->prepare($sql); #执行语句 $stmt->execute($params); $res = $stmt->fetchAll(PDO::FETCH_ASSOC); return $res; } }
以上就介绍了我的PDO 类,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。