php實現(xiàn)基于pdo的事務(wù)處理方法示例
本文實例講述了php實現(xiàn)基于pdo的事務(wù)處理方法。分享給大家供大家參考,具體如下:
實例1:
try {} catch () {} 形式
<?php
$dsn = 'mysql:dbname=cheyun_cms;host=127.0.0.1';
$user = 'root';
$password = '111111';
//采用預(yù)處理+事務(wù)處理執(zhí)行SQL操作
//1.連接數(shù)據(jù)庫
try {
$pdo = new PDO($dsn, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("數(shù)據(jù)庫連接失敗".$e->getMessage());
}
//2.執(zhí)行數(shù)據(jù)操作
try{
//開啟事物,此時會關(guān)閉自動提交
$pdo->beginTransaction();
$sql = "insert into cy_log (logid, value, action, file) values (?, ?, ?, ?)";
$stmt = $pdo->prepare($sql);
//傳入?yún)?shù)
$stmt->execute(array(null,"test4","w",11));
$stmt->execute(array(null,"test5","w",11));
$stmt->execute(array(null,"test3","w",11));
//提交事物,并且 數(shù)據(jù)庫連接返回到自動提交模式
$pdo->commit();
}catch(PDOException $e){
echo '執(zhí)行失敗'.$e->getMessage();
//如果數(shù)據(jù)庫被設(shè)置成自動提交模式,rollback 在回滾事務(wù)之后將恢復(fù)自動提交模式。
//包括 MySQL 在內(nèi)的一些數(shù)據(jù)庫, 當(dāng)在一個事務(wù)內(nèi)有類似刪除或創(chuàng)建數(shù)據(jù)表等 DLL 語句時,會自動導(dǎo)致一個隱式地提交。
//隱式地提交將無法回滾此事務(wù)范圍內(nèi)的任何更改。即 DDL 語句無法回滾
$pdo->rollback();
}
實例2:
if…else…形式
<?php
$dsn = 'mysql:dbname=cheyun_cms;host=127.0.0.1';
$user = 'root';
$password = '111111';
//采用預(yù)處理+事務(wù)處理執(zhí)行SQL操作
//1.連接數(shù)據(jù)庫
try {
$pdo = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
die("數(shù)據(jù)庫連接失敗".$e->getMessage());
}
//2.執(zhí)行數(shù)據(jù)操作
//開啟事物
$pdo->beginTransaction();
$sql = "insert into cy_log (logid, value, action, file) values (?, ?, ?, ?)";
$stmt = $pdo->prepare($sql);
$datalist = array(
array(null,"test9","w",11),
array(null,"test10","w",11),
array(null,"test11","w",11)
);
//是否提交標志位
$isCommit = true;
foreach($datalist as $data){
$stmt->execute($data);
if($stmt->errorCode()>0){
//回滾
$pdo->rollback();
$isCommit = false;
break;
}
}
if($isCommit){
//提交事物
$pdo->commit();
}
注意:
數(shù)據(jù)表需要 InnoDB 類型
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《PHP基于pdo操作數(shù)據(jù)庫技巧總結(jié)》、《php+Oracle數(shù)據(jù)庫程序設(shè)計技巧總結(jié)》、《PHP+MongoDB數(shù)據(jù)庫操作技巧大全》、《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設(shè)計有所幫助。
相關(guān)文章
PHP基于mssql擴展遠程連接MSSQL的簡單實現(xiàn)方法
這篇文章主要介紹了PHP基于mssql擴展遠程連接MSSQL的簡單實現(xiàn)方法,涉及php操作mssql的簡單連接、查詢、遍歷與輸出相關(guān)操作技巧,需要的朋友可以參考下2016-10-10

