PDO中构建事务处理的应用程序

 1 <meta http-equiv="Content-Type" content="text/html";charse="utf-8" />
 2 <?php
 3     
 4     /* 将一系列的更新操作放到beginTransaction()和commit()函数中调用,并通过try块执行,就可以保证在更改之前完成,其他人无法看到 */
 5     $dsn = 'mysql:dbname=test;host=localhost';
 6     $username = 'root';
 7     $password = '';
 8     $opt = array(PDO::ATTR_PERSISTENT => true);
 9     
10     //持续连接数据库
11     try{
12         $dbh = new PDO($dsn,$username,$password,$opt);
13     }catch(PDOException $e){
14         echo '数据库连接失败'.$e -> getMessage();
15     }
16     
17     $dbh -> setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);//设置PDO异常处理模式
18     $dbh -> setAttribute(PDO::ATTR_AUTOCOMMIT,0);//关闭自动提交
19     
20     try{
21         $price = 80;
22         $dbh -> beginTransaction();//开始事备
23         
24         $affected_row = $dbh -> exec("update account set cash = cash-{$price} where name='userA'");
25         if($affected_row > 0){
26             echo "userA成功转出{$price}元人民币<br>";
27         }else{
28             throw new PDOException('usrA转出失败');
29         }
30         
31         $affected_row = $dbh -> exec("update account set cash = cash + {$price} where name='userB'");
32         if($affected_row > 0){
33             echo "userB成功转入{$price}元人民币<br>";
34         }else{
35             throw new PDOException('usrB转入成功');
36         }
37         
38         echo '交易成功';
39         $dbh -> commit();//如果执行到此处说明两次语句执行成功,整个事务成功
40         
41     }catch(PDOException $e){
42         echo "交易失败".$e -> getMessage();
43         $dbh -> rollback();//如果事务执行失败,回滚事务
44     }
45     
46     $dbh -> setAttribute(PDO::ATTR_AUTOCOMMIT,1);//重新打开自动提交
View Code

 

posted @ 2016-01-16 21:31  banshaohuan  阅读(172)  评论(0编辑  收藏  举报