layout: post
title: "Learn-more-PDO"
date: 2016-05-19 18:47:27 +0800
comments: true
categories: [php,mysql]
前段时间在做手机归属地查询的Demo时突然发现自己对PDO还是太生疏,一直都是用的以前的代码。很多都不太了解,于是重新系统的学习了一下PDO类。
什么是PDO
PDO(PHP Data Object)数据库访问抽象层,统一各种数据库的访问接口。
特性
- 编码一致性
- 灵活性
- 高性能
- 面向对象特性
PDO的安装与配置,和PHP其他扩展的开启一样,只需要在php.ini
里设置即可,这里就不多说了。
PDO连接数据库
<?php
//通过参数形式连接数据库
try{
$dsn='mysql:host=localhost;dbname=test';
$username='root';
$passwd='root';
$pdo=new PDO($dsn, $username, $passwd);
var_dump($pdo);
}catch(PDOException $e){
echo $e->getMessage();
}
[图片上传失败...(image-671274-1532593830112)]
PDO exec
增删改,返回得是受影响的行数
<?php
try{
$pdo=new PDO('mysql:host=localhost;dbname=test','root','root');
//exec():执行一条sql语句并返回其受影响的记录的条数,如果没有受影响的记录,他返回0
//exec对于select没有作用
$sql=<<<EOF
CREATE TABLE IF NOT EXISTS user(
id INT UNSIGNED AUTO_INCREMENT KEY,
username VARCHAR(20) NOT NULL UNIQUE,
password CHAR(32) NOT NULL,
email VARCHAR(30) NOT NULL
);
EOF;
//$sql='INSERT user(username,password,email) VALUES("reton","reton","reton@qq.com")';
//$res=$pdo->exec($sql);
//echo '受影响的记录的条数为:'.$res,'<br/>';
//$pdo->lastInsertId():得到新插入记录的ID号
//echo '最后插入的ID号为'.$pdo->lastInsertId();
$res=$pdo->exec($sql);
var_dump($res);
$sql='INSERT user(username,password,email) VALUES("reton","'.md5('reton').'","test@qq.com")';
//echo $sql;
$res=$pdo->exec($sql);
echo $res;
}catch(PDOException $e){
echo $e->getMessage();
}
PDO error 获取错误信息
获取错误码和错误信息
<?php
header('content-type:text/html;charset=utf-8');
try{
$pdo=new PDO('mysql:host=localhost;dbname=test','root','root');
$sql='delete from user12 where id=1';
$res=$pdo->exec($sql);
//echo $res.'条记录被影响';
//var_dump($res);
if($res===false){
//$pdo->errorCode():SQLSTATE的值
echo $pdo->errorCode();
echo '<hr/>';
//$pdo->errorInfo():返回的错误信息的数组,数组中包含3个单元
//0=>SQLSTATE,1=>CODE,2=>INFO
$errInfo=$pdo->errorInfo();
print_r($errInfo);
}
// echo '<hr/>';
// echo $pdo->lastInsertId();
}catch(PDOException $e){
echo $e->getMessage();
}
PDO query
执行查询,返回的是PDOStatement对象
<?php
header('content-type:text/html;charset=utf-8');
try{
$pdo=new PDO('mysql:host=localhost;dbname=test','root','root');
//$sql='select * from user where id=2';
$sql='select id,username,email from user';
//$pdo->query($sql),执行SQL语句,返回PDOStatement对象
$stmt=$pdo->query($sql);
var_dump($stmt);
echo '<hr/>';
foreach($stmt as $row){
//print_r($row);
echo '编号:'.$row['id'],'<br/>';
echo '用户名:'.$row['password'],'<br/>';
echo '邮箱:'.$row['email'],'<br/>';
echo '<hr/>';
}
}catch(PDOException $e){
echo $e->getMessage();
}
PDO prepare
prepare 准备方法
header('content-type:text/html;charset=utf-8');
try{
$pdo=new PDO('mysql:host=localhost;dbname=test','root','root');
$sql='select * from user where username="reton"';
//prepare($sql):准备SQL语句
$stmt=$pdo->prepare($sql);
//execute():执行预处理语句
$res=$stmt->execute();
//var_dump($res);
//fetch():得到结果集中的一条记录
$row=$stmt->fetch();
print_r($row);
//var_dump($stmt);
}catch(PDOException $e){
echo $e->getMessage();
}
<?php
header('content-type:text/html;charset=utf-8');
try{
$pdo=new PDO('mysql:host=localhost;dbname=test','root','root');
$sql='select * from user';
$stmt=$pdo->prepare($sql);
$res=$stmt->execute();
// if($res){
// while($row=$stmt->fetch()){
// print_r($row);
// echo '<hr/>';
// }
// }
$rows=$stmt->fetchAll();
print_r($rows);
//var_dump($stmt);
}catch(PDOException $e){
echo $e->getMessage();
}
<?php
header('content-type:text/html;charset=utf-8');
try{
$pdo=new PDO('mysql:host=localhost;dbname=test','root','root');
$sql='select * from user';
$stmt=$pdo->prepare($sql);
$res=$stmt->execute();
// if($res){
// while($row=$stmt->fetch(PDO::FETCH_OBJ)){//返回对象
// print_r($row);
// echo '<hr/>';
// }
// }
// $rows=$stmt->fetchAll(PDO::FETCH_ASSOC);//返回关联数组BOTH为数组加索引
// print_r($rows);
echo '<hr/>';
$stmt->setFetchMode(PDO::FETCH_ASSOC);//set了就不用传参了
//var_dump($stmt);
$rows=$stmt->fetchAll();
print_r($rows);
}catch(PDOException $e){
echo $e->getMessage();
}
PDO getAttribute
获得数据库连接属性
<?php
header('content-type:text/html;charset=utf-8');
try{
$dsn='mysql:host=localhost;dbname=test';
$username='root';
$passwd='root';
$pdo=new PDO($dsn, $username, $passwd);
echo '自动提交:'.$pdo->getAttribute(PDO::ATTR_AUTOCOMMIT);
echo '<br/>';
echo 'PDO默认的错误处理模式:'.$pdo->getAttribute(PDO::ATTR_ERRMODE);
$pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, 0);
echo '<br/>';
echo '自动提交:'.$pdo->getAttribute(PDO::ATTR_AUTOCOMMIT);
}catch(PDOException $e){
echo $e->getMessage();
}
获取常用属性 并不是所有环境都支持一下的属性
<?php
header('content-type:text/html;charset=utf-8');
try{
$dsn='mysql:host=localhost;dbname=test';
$username='root';
$passwd='root';
$pdo=new PDO($dsn, $username, $passwd);
$attrArr=array(
'AUTOCOMMIT','ERRMODE','CASE','PERSISTENT','TIMEOUT','ORACLE_NULLS',
'SERVER_INFO','SERVER_VERSION','CLIENT_VERSION','CONNECTION_STATUS'
);
foreach($attrArr as $attr){
echo "PDO::ATTR_$attr: ";
echo $pdo->getAttribute(constant("PDO::ATTR_$attr")),'<br/>';
}
}catch(PDOException $e){
echo $e->getMessage();
}
PDO setAttribute
设置数据库连接属性
<?php
header('content-type:text/html;charset=utf-8');
try{
$dsn='mysql:host=localhost;dbname=test';
$username='root';
$passwd='root';
$options=array(PDO::ATTR_AUTOCOMMIT=>0,PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION);
$pdo=new PDO($dsn, $username, $passwd, $options);
echo $pdo->getAttribute(PDO::ATTR_AUTOCOMMIT);
echo '<br/>';
echo $pdo->getAttribute(PDO::ATTR_ERRMODE);
}catch(PDOException $e){
echo $e->getMessage();
}
PDOStatement 对象的使用
quote防注入
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
</head>
<body>
<form action='doAction2.php' method='post'>
用户名:<input type='text' name='username' /><br/>
密码:<input type='password' name='password'/><br/>
<input type='submit' value='登陆'/>
</form>
</body>
</html>
<?php
<?php
header('content-type:text/html;charset=utf-8');
$username=$_POST['username'];
$password=$_POST['password'];
try{
$pdo=new PDO('mysql:host=localhost;dbname=test','root','root');
//echo $pdo->quote($username);
//$sql="select * from user where username='{$username}' and password='{$password}'";
//echo $sql;
//通过quote():返回带引号的字符串,过滤字符串中的特殊字符
$username=$pdo->quote($username);
$sql="select * from user where username={$username} and password='{$password}'";
echo $sql;
$stmt=$pdo->query($sql);
//PDOStatement对象的方法:rouCount():对于select操作返回的结果集中记录的条数,
//对于INSERT、UPDATE、DELETE返回受影响的记录的条数
echo $stmt->rowCount();
}catch(PDOException $e){
echo $e->getMessage();
}
预处理语句的占位符
第一种用:xxx
<?php
header('content-type:text/html;charset=utf-8');
$username=$_POST['username'];
$password=$_POST['password'];
try{
$pdo=new PDO('mysql:host=localhost;dbname=test','root','root');
$sql="select * from user where username=:username and password=:password"; //占位
$stmt=$pdo->prepare($sql);
$stmt->execute(array(":username"=>$username,":password"=>$password));赋值
echo $stmt->rowCount();
}catch(PDOException $e){
echo $e->getMessage();
}
第二种用?
<?php
header('content-type:text/html;charset=utf-8');
$username=$_POST['username'];
$password=$_POST['password'];
try{
$pdo=new PDO('mysql:host=localhost;dbname=test','root','root');
$sql="select * from user where username=? and password=?";
$stmt=$pdo->prepare($sql);
$stmt->execute(array($username,$password));
echo $stmt->rowCount();
}catch(PDOException $e){
echo $e->getMessage();
}
bindParam()方法绑定参数到变量
<?php
header('content-type:text/html;charset=utf-8');
try{
$pdo=new PDO('mysql:host=localhost;dbname=test','root','root');
$sql="INSERT user(username,password,email) VALUES(:username,:password,:email)";
$stmt=$pdo->prepare($sql);
$stmt->bindParam(":username",$username,PDO::PARAM_STR);//绑定参数,被绑定的项,绑定的地址(不能直接写值),参数类型。如果是用的?第一个参数要写1,2,3。表示第几个占位符
$stmt->bindParam(":password",$password,PDO::PARAM_STR);
$stmt->bindParam(":email",$email);
$username='imooc1';
$password='imooc1';
$email='imooc1@imooc.com';
$stmt->execute();
$username='MR.KING1';
$password='MR.KING1';
$email='MR.KING1@imooc.com';
$stmt->execute();
echo $stmt->rowCount();
}catch(PDOException $e){
echo $e->getMessage();
}
PDO错误处理模式
<?php
/*
PDO::ERRMODE_SLIENT:默认模式,静默模式
PDO::ERRMODE_WARNING:警告模式
PDO::ERRMODE_EXCEPTION:异常模式
*/
try{
$pdo=new PDO('mysql:host=localhost;dbname=test','root','root');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql='SELECT * FROM noneTable';
$pdo->query($sql);
echo $pdo->errorCode();
echo '<br/>';
print_r($pdo->errorInfo());
}catch(PDOException $e){
echo $e->getMessage();
}
[图片上传失败...(image-dc987-1532593830113)]
PDO事务处理模式
<?php
header('content-type:text/html;charset=utf-8');
try{
$dsn='mysql:host=localhost;dbname=test';
$username='root';
$passwd='root';
$options=array(PDO::ATTR_AUTOCOMMIT,0);
$pdo=new PDO($dsn, $username, $passwd, $options);
var_dump($pdo->inTransaction());
//开启事务
$pdo->beginTransaction();
var_dump($pdo->inTransaction());
//$sql='UPDATE userAccount SET money=money-2000 WHERE username="imooc"';
$sql='UPDATE userAccount SET money=money-2000 WHERE username="imooc"';
$res1=$pdo->exec($sql);
if($res1==0){
throw new PDOException('imooc 转账失败');
}
$res2=$pdo->exec('UPDATE userAccount SET money=money+2000 WHERE username="king1"');
if($res2==0){
throw new PDOException('king 接收失败');
}
//提交事务
$pdo->commit();
}catch(PDOException $e){
//回滚事务
$pdo->rollBack();
echo $e->getMessage();
}
PDO操作类封装
<?php
/**
*
*/
class PdoMySQL
{
public static $config=array();//设置链接参数,配置信息
public static $link=null;//保存链接标识符
public static $pconnect=false;//是否开启长链接
public static $dbVersion=null;//保存数据库版本
public static $connected=false;//是否链接成共
public static $PDOStatement=null;//保存PDOStatement对象
public static $queryStr = null;//保存最后执行的操作
public static $error=null;//保存错误信息
public static $lastInsertId=null;//最后插入记录的id
public static $numRows=0;//保存上一步影响的行数
function __construct($dbConfig='')
{
if(!class_exists("PDO")){
self::throw_excption("不支持PDO,请先开启");
}
if(!is_array($dbConfig)){
$dbConfig=array(
"hostname" => DB_HOST,
"username" => DB_USER,
"password" => DB_PWD,
"database" => DB_NAME,
"hostport" => DB_PORT,
"dbms" => DB_TYPE,
"dsn" =>DB_TYPE.":host=".DB_HOST.";dbname=".DB_NAME
);
}
if(empty($dbConfig['hostname']))self::throw_excption("没有定义数据库配置,请先定义。");
self::$config=$dbConfig;
if(empty(self::$config['params']))self::$config['params']=array();
if(!isset(self::$link)){
$configs=self::$config;
if(self::$pconnect){
//开启长链接,添加到配置数组中
$configs['params'][constant("PDO::ATTR_PERSISTENT")]=true;
}
try {
self::$link=new PDO($configs['dsn'],$configs['username'],$configs['password'],$configs['params']);
} catch (PDOException $e) {
self::throw_excption($e->getMessage());
}
if(!self::$link){
self::throw_excption("PDO链接错误");
return false;
}
self::$link->exec('SET NAMES'.DB_CHARSET);
self::$dbVersion=self::$link->getAttribute(constant("PDO::ATTR_SERVER_VERSION"));
self::$connected=true;
unset($configs);
}
}
/**
* 得到所有记录
* @param [type] $sql [description]
* @return [type] [description]
*/
public static function getAll($sql=null)
{
if($sql!=null){
self::query($sql);
}
$result=self::$PDOStatement->fetchAll(constant("PDO::FETCH_ASSOC"));
return $result;
}
/**
* 得到结果集中的一条记录
* @param [type] $sql [description]
* @return [type] [description]
*/
public static function getRow($sql=null)
{
if($sql!=null){
self::query($sql);
}
$result =self::$PDOStatement->fetch(constant("PDO::FETCH_ASSOC"));
return $result;
}
/**
* 解析字段
* @param [type] $fields [description]
* @return [type] [description]
*/
public static function parseFields($fields)
{
if(is_array($fields)){
array_walk($fields,array('PdoMySQL','addSpecilChar'));
$fieldsStr=implode(',',$fields);
}elseif (is_string($fields)&&!empty($fields)) {
if(strpos($fields,'`')===false){
$fields=explode(',',$fields);
array_walk($fields,array('PdoMySQL','addSpecilChar'));
$fieldsStr=implode(',',$fields);
}else {
$fieldsStr=$fields;
}
}else {
$fieldsStr='*';
}
return $fieldsStr;
}
/**
* 通过反引号引用字段,
* @param [type] $value [description]
*/
public static function addSpecilChar(&$value)
{
if($value==='*'||strpos($value,'.')!==false||strpos($value,'`')!==false){
//不用做处理
}elseif (strpos($value,'`')===false) {
# code...
$value='`'.trim($value).'`';
}
return $value;
}
/**
* 根据主键查记录
* @param [type] $tabName [description]
* @param [type] $priId [description]
* @param string $fields [description]
* @return [type] [description]
*/
public static function findById($tabName,$priId,$fields='*')
{
$sql="SELECT %s FROM %s WHERE id =%d";
return self::getRow(sprintf($sql,self::parseFields($fields),$tabName,$priId));
}
/**
* 执行普通查询,
* @param [type] $tables [description]
* @param [type] $where [description]
* @param string $fields [description]
* @param [type] $group [description]
* @param [type] $having [description]
* @param [type] $order [description]
* @param [type] $limit [description]
* @return [type] [description]
*/
public static function find($tables,$where=null,$fields='*',$group=null,$having=null,$order=null,$limit=null)
{
$sql='SELECT '.self::parseFields($fields).' FROM '.$tables.self::parseWhere($where).self::parseGroup($group).self::parseHaving($having).self::parseOrder($order).self::parseLimit($limit);
$dataAll=self::getAll($sql);
// if(count($dataAll)==1){
// $rlt=$dataAll[0];
// }else {
// $rlt=$dataAll;
// }
// return $rlt;
return count($dataAll)==1?$dataAll[0]:$dataAll;
}
/**
* 添加记录
* array(
*
* )
* @param string $value [description]
*/
public static function add($data,$table)
{
$keys=array_keys($data);
array_walk($keys,array('PdoMySQL','addSpecilChar'));
$fieldsStr=join(',',$keys);
$values="'".join("','",array_values($data))."'";
$sql="INSERT {$table}({$fieldsStr}) VALUES({$values})";
return self::execute($sql);
}
/**
* 更新记录
* @param [array] $data [description]
* @param [string] $table [description]
* @param [string] $where [description]
* @param [string] $order [description]
* @param [string] $limit [description]
* @return [type] [description]
*/
public static function update($data,$table,$where=null,$order=null,$limit=null)
{
foreach ($data as $key => $value) {
$set.=$key."='".$value."',";
}
$sets=rtrim($sets,',');
$sql="UPDATE {$table} SET {$sets} ".self::parseWhere($where).self::parseOrder($order).self::parseLimit($limit);
return self::execute($sql);
}
/**
* 删除记录
* @param [type] $table [description]
* @param [type] $where [description]
* @param [type] $order [description]
* @param integer $limit [description]
* @return [type] [description]
*/
public static function delete($table,$where=null,$order=null,$limit=0)
{
$sql="delete from {$table} " .self::parseWhere($where).self::parseOrder($order).self::parseLimit($limit);
return self::execute($sql);
}
/**
* 得到最后执行的SQL语句
* @return [type] [description]
*/
public static function getLastSql()
{
$link=self::$link;
if(!$link){
return false;
}
return self::$queryStr;
}
/**
* 得到上一步插入操作的ID
*/
public static function getLsetInsertId()
{
$link=self::$link;
if(!$link)return false;
return self::$lastInsertId;
}
/**
* 得到数据库版本
*/
public static function getDbVersion()
{
$link=self::$link;
if(!$link)return false;
return self::$dbVersion;
}
/**
* 得到数据库有哪些表
* @return [type] [description]
*/
public static function showTables()
{
$tables=array();
if(self::query('SHOW TABLES')){
$result = self::getAll();
foreach ($result as $key => $value) {
# code...
$tables[$key]=current($value);
}
}
return $tables;
}
/**
* 解析where条件
* @param [type] $where [description]
* @return [type] [description]
*/
public static function parseWhere($where)
{
$whereStr='';
if(is_string($where)&&!empty($where)){
$whereStr=$where;
}
return empty($whereStr)?'':' WHERE '.$whereStr;
}
/**
* 解析分组
* @param [type] $group [description]
* @return [type] [description]
*/
public static function parseGroup($group)
{
$groupStr='';
if(is_array($group)){
$groupStr.=' GROUP BY '.implode(',',$group);
}elseif (is_string($group)&&!empty($group)) {
$groupStr.=' GROUP BY '.$group;
}
return empty($groupStr)?'':$groupStr;
}
/**
* 对分组结果通过Having子句进行二次删选
* @param [type] $having [description]
* @return [type] [description]
*/
public static function parseHaving($having)
{
$havingStr='';
if(is_string($having)&&!empty($having)){
$havingStr.=' HAVING '.$having;
}
return $havingStr;
}
/**
* 解析order by
* @param [type] $order [description]
* @return [type] [description]
*/
public static function parseOrder($order)
{
$orderStr='';
if(is_array($order)){
$orderStr.=' ORDER BY '.join(',',$order);
}elseif (is_string($order)&&!empty($order)) {
$orderStr.=' ORDER BY '.$order;
# code...
}
return $orderStr;
}
/**
* 解析限制条数
* limit 3
* limit 0,3
* @param [type] $limit [description]
* @return [type] [description]
*/
public static function parseLimit($limit)
{
$limitStr='';
if(is_array($limit)){
if(count($limit)>1){
$limitStr.=' LIMIT '.$limit[0].','.$limit[1];
}else {
$limitStr.=' LIMIT '.$limit[0];
}
}elseif (is_string($limit)&&!empty($limit)) {
$limitStr.=' LIMIT '.$limit;
}
return $limitStr;
}
/**
* 执行增删改,返回受影响的条数
* @param [type] $sql [description]
* @return [type] [description]
*/
public static function execute($sql=null)
{
$link=self::$link;
if(!$link) return false;
self::$queryStr=$sql;
if(!empty(self::$PDOStatement))self::free();
$result=$link->exec(self::$queryStr);
self::haveErrorThrowException();
if($result){
self::$lastInsertId=$link->lastInsertId();
self::$numRows=$result;;
return self::$numRows;
}else {
return false;
}
}
/**
*释放结果集
* @return [type] [description]
*/
public static function free()
{
self::$PDOStatement=null;
}
/**
* 执行sql语句
* @param string $sql [description]
* @return [type] [description]
*/
public static function query($sql='')
{
$link=self::$link;
if(!$link)return false;
//判断之前是否有结果集,如果有的话,释放结果集
if(!empty(self::$link)) self::free();
self::$queryStr=$sql;
self::$PDOStatement=$link->prepare(self::$queryStr);
$res = self::$PDOStatement->execute();
self::haveErrorThrowException();
return $res;
}
/**
* 如果有错误,抛出
* @return [type] [description]
*/
public static function haveErrorThrowException()
{
$obj=empty(self::$PDOStatement)?self::$link:self::$PDOStatement;
$arrError=$obj->errorInfo();
// print_r($arrError);
if($arrError[0]!='00000'){
self::$error="SQLSTATE".$arrError[0]."SQL Error".$arrError[2]."<br/>Error SQL".self::$queryStr;
self::throw_excption(self::$error);
return false;
}
if(self::$queryStr==""){
self::throw_excption('没有执行的SQL语句');
return false;
}
}
/**
* 自定义错误处理
* @param [type] $errMsg [description]
* @return [type] [description]
*/
public function throw_excption($errMsg)
{
echo "<div style='width:80%;background-color:#ABCDEF;colod:black;font-size:20px;padding:20px 0px;'>
".$errMsg."
</div>";
}
/**
* 销毁链接对象,关闭数据库。
* @return [type] [description]
*/
public static function close()
{
self::$link=null;
}
}
require_once"config.php";
// $PdoMySQL=new PdoMySQL;
// // var_dump($PdoMySQL);
// // $sql="insert user (username,password,email) values('reane23','sdf','sdf')";
// $tables='user';
// $res=$PdoMySQL->find($tables,'id>=19','*',null,null,null,'3');
// var_dump($res);
// echo $PdoMySQL::$lastInsertId;
// print_r($res);
<?php
define("DB_HOST","localhost");
define("DB_USER","root");
define("DB_PWD","123456");
define("DB_NAME","test");
define("DB_PORT","3306");
define("DB_TYPE","mysql");
define("DB_CHARSET","utf8");
网友评论