PHP使用PDO事務操做數據庫。php
參考文章:html
http://php.ncong.com/mysql/pdo/pdo_shiwu.htmlmysql
上代碼:sql
<!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <?php try { $pdo = new PDO("mysql:host=localhost;dbname=test", "root", "XXXXXX"); //設置錯誤使用異常的模式 $pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //關閉自動提交 $pdo-> setAttribute(PDO::ATTR_AUTOCOMMIT, 0); } catch (PDOException $e) { echo sprintf("Exception message=%s", $e->getMessage()); exit(); } $strSql = "UPDATE mytable SET headline='哈哈' WHERE id=:id"; $pdo->beginTransaction(); try { for ($i = 1; $i <= 5; $i++) { $stmt = $pdo->prepare($strSql); $affectedRows = $stmt->execute(array("id"=>$i)); if ($affectedRows > 0) { echo sprintf("update success id=%s<br/>", $i); } else { echo sprintf("update false id=%s", $i); } } $pdo->commit(); } catch (PDOException $e) { echo sprintf("Exception message=%s", $e->getMessage()); $pdo->rollBack(); exit(); } // 須要打開自動提交 $pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, 1); echo "<hr/>"; $stm = $pdo->prepare("SELECT id, headline, create_time FROM mytable"); $stm->execute(); $stm->bindColumn(1, $id); $stm->bindColumn("headline", $headline); $stm->bindColumn(3, $createTime); while ($stm->fetch(PDO::FETCH_BOUND)) { echo "<p>", $id, " - " , $headline, " - ", $createTime, "</p>"; } ?> </body> </html>