本文實例講述了php+Mysqli利用事務處理轉賬問題的方法。分享給大家供大家參考。具體實現方法如下:
<?php 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程序設計有所幫助。