標籤:
本文執行個體講述了php+Mysqli利用交易處理轉賬問題的方法。分享給大家供大家參考,沒什麼過多的文字好說的,直接看代碼來得快
<?php /**php+Mysqli利用交易處理轉賬問題執行個體 * author http://www.lai18.com * date 2015-04-19 * version 1 **/ header("Content-type:text/html; charset=utf-8"); $mysqli = new mysqli("localhost", "root", "064319", "php"); $mysqli->set_charset("utf8"); if($mysqli->connect_errno) { die('資料庫連接失敗'.$mysqli->connect_error); } $mysqli->autocommit(false); //自動認可模式設為false $flag = true; //事務是否成功執行的標誌 $query = "update account set balance=balance-1000 where id=3"; $result = $mysqli->query($query); $affected_count = $mysqli->affected_rows; if(!result || $affected_count == 0) { //失敗 $flag = false; } $query = "update account set balance=balance+1000 where id=2"; $result = $mysqli->query($query); $affected_count = $mysqli->affected_rows; if(!$result || $affected_count == 0) { $flag = false; } if($flag) { $mysqli->commit(); echo '轉賬成功'; } else { $mysqli->rollback(); echo '轉賬失敗'; } $mysqli->autocommit(true); //重新設定事務為自動認可 $mysqli->close(); ?>
php+Mysqli利用交易處理轉賬問題執行個體