PHP PDO事務回滾
阿新 • • 發佈:2019-01-04
<?php try{ $pdo=new pdo("mysql:host=localhost;dbname=xsphpdb", "root", "123456", array(PDO::ATTR_AUTOCOMMIT=>0));//最後是關閉自動提交 //$pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, 0);//這個是通過設定屬性方法進行關閉自動提交和上面的功能一樣 $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);//開啟異常處理 }catch(PDOException $e){ echo "資料庫連線失敗:".$e->getMessage(); exit; } /* * 事務處理 * */ try{ $pdo->beginTransaction();//開啟事務處理 $price=500; $sql="update zhanghao set price=price-{$price} where id=1"; $affected_rows=$pdo->exec($sql); if(!$affected_rows) throw new PDOException("張三轉出失敗");//那個錯誤丟擲異常 $sql="update zhanghao set price=price+{$price} where id=3"; $affected_rows=$pdo->exec($sql); if(!$affected_rows) throw new PDOException("向李四轉入失敗"); echo "交易成功!"; $pdo->commit();//交易成功就提交 }catch(PDOException $e){ echo $e->getMessage(); $pdo->rollback(); } $pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, 1);//自動提交,如果最後不自動提交,轉賬是不成功的 //設定錯誤報告模式 ERRMODE_SILENT ERRMODE_WARNING