CREATE TABLE account(
id TINYINT UNSIGNED AUTO_INCREMENT KEY,
username VARCHAR(20) NOT NULL,
money FLOAT(6,2)
);
INSERT account(username,money) VALUES('king',1000);
INSERT account(username,money) VALUES('queen',500);
$mysqli->autocommit(false);
$mysqli->commit();
$mysqli->rollback();
<?php
header('content-type:text/html;charset=utf-8');
$mysqli = new mysqli('localhost', 'root', '', 'test');
if ($mysqli->errno) {
die('Connect Error ' . $mysqli->error);
}
$mysqli->set_charset('UTF8');
//先关闭自动提交功能
$mysqli->autocommit(false);
$sql = "UPDATE account SET money=money-200 WHERE username='king'";
$res = $mysqli->query($sql);
$res_affect = $mysqli->affected_rows;
$sql1 = 'UPDATE account SET money=money+200 WHERE username="queen"';
$res1 = $mysqli->query($sql1);
$res1_affect = $mysqli->affected_rows;
if ($res && $res_affect > 0 && $res1 && $res1_affect > 0) {
$mysqli->commit();
echo "转账成功<br/>";
$mysqli->autocommit(true);
} else {
$mysqli->rollback();
echo "转账失败<br/>";
}
$mysqli->close();
?>