我正在尝试使用mysql数据库(InnoDB)测试php中的事务,但回滚无效...
这是我的代码
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "test";
$conn = mysqli_connect($servername, $username, $password, $database);
mysqli_autocommit($conn, FALSE);
mysqli_query($conn,"update person set Balance = 300 where Name = 'Jay'");
if ($conn->affected_rows > 0) {
mysqli_commit($conn);
echo "First Commited <br>";
mysqli_query($conn,"update person set Balance = 3000 where Name = 'Rv'");
if($conn->affected_rows > 0) {
mysqli_commit($conn);
echo "Second Commited <br>";
}else {
mysqli_rollback($conn);
echo "First rollback <br>";
}
}
mysqli_close($conn);
?>
有什么不对吗? (我也在php中尝试面向对象的风格,请参阅here)
SHOW CREATE TABLE人查询结果
答案 0 :(得分:0)
您在第二次更新完成之前提交了第一次更新,所以......
mysqli_autocommit($conn, FALSE);
mysqli_query($conn,"update person set Balance = 300 where Name = 'Jay'");
if ($conn->affected_rows > 0) {
// mysqli_commit($conn); // Remove this line
// echo "First Commited <br>";
mysqli_query($conn,"update person set Balance = 3000 where Name = 'Rv'");
if($conn->affected_rows > 0) {
mysqli_commit($conn);
echo "Second Commited <br>";
}else {
mysqli_rollback($conn);
echo "First rollback <br>";
}
}