您当前的位置: 首页 > 学无止境 > 网站建设 网站首页网站建设
pdo对象中方法的使用详细介绍
发布时间:2015-12-03 16:47:23编辑:雪饮阅读()
pdo下执行无结果集sql语句:
try{$pdo=new PDO("mysql:host=localhost;dbname=test2","root","root");}
catch(PDOException $e){echo "数据库连接失败".$e->getMessage();exit;}
//pdo下执行无结果集语句
echo "影响的行数".$pdo->exec("insert into shops(name,price,num,desn) values('aa',12.1,10,'good')");
pdo下获取sql执行错误号以及错误信息:
try{$pdo=new PDO("mysql:host=localhost;dbname=test2","root","root");}
catch(PDOException $e){echo "数据库连接失败".$e->getMessage();exit;}
//pdo下执行无结果集语句
$affected_row=$pdo->exec("insert into shops(name,price,num,desn) values('aa',12.1,10,'good')");
if(!$affected_row){
echo "错误号:".$pdo->errorCode()."<br/>";
echo "错误信息:".$pdo->errorInfo();
}
else{
echo "执行成功";
}
pdo下获取最后插入id:
try{
$pdo=new PDO("mysql:host=localhost;dbname=test2","root","root");
//pdo下执行无结果集语句
$affected_row=$pdo->exec("insert into shops(name,price,num,desn) values('aa',12.1,10,'good')");
echo "最后插入id为:".$pdo->lastInsertId();
}
catch(PDOException $e){echo "数据库连接失败".$e->getMessage();exit;}
pdo下遍历结果集的每条数据:
header("Content-type:text/html;charset=utf-8;");
try{
$pdo=new PDO("mysql:host=localhost;dbname=test2","root","root");
//pdo下执行无结果集语句
$stmt=$pdo->query("select * from shops");
echo "所有结果集数组对象:".var_dump($stmt)."<br/>";
echo "<hr/>遍历出每条数据数组<hr/>";
foreach($stmt as $row){
print_r($row);
echo "<br/>";
}
}
catch(PDOException $e){echo "数据库连接失败".$e->getMessage();exit;}
pdo的事务处理:
mysql中先关闭自动提交: set autocommit=0;
mysql中先开启事务处理(事务处理所必须条件):start transaction;
注意:事务处理所在表引擎必须是InnoDB
pdo事务处理完整案例(注意:mysql中先要手动关闭自动提交,否则将会在pdo更新数据成功后,mysql中需要rollback回滚一次才能显示出来更新后的数据):
header("Content-type:text/html;charset=utf-8;");
try{
$pdo=new PDO("mysql:host=localhost;dbname=test2","root","root",array(PDO::ATTR_AUTOCOMMIT=>0));
//PDO::ATTR_AUTOCOMMIT=>0,pdo中关闭mysql自动提交
$pdo->beginTransaction();//pdo中开启mysql事务处理
$price=5;
$sql="update shops set price=price-$price where id=1";
$affected_row=$pdo->exec($sql);
if(!$affected_row){throw new PDOException("向b转出失败");}
$sql2="update shops set price=price+$price where id=2";
$affected_row=$pdo->exec($sql2);
if(!$affected_row){throw new PDOException("从a转入失败");}
echo "交易成功";
$pdo->commit();
}
catch(PDOException $e){echo "数据库连接失败".$e->getMessage();$pdo->rollBack();}
$pdo->setAttribute(PDO::ATTR_AUTOCOMMIT,true);
关键字词:pdo,方法
上一篇:pdo介绍安装及对象的初始化