MySQLi事务控制

事务就是将多个逻辑工作组合成一个执行单元的数据库操作(一起成功一起失败)

$mysqli -> autocommit(bool);//开启事务

$mysqli -> rollback();//回滚事务

$mysqli -> commit();事务提交

实例

<?php
header("content-type:text/html;charset=utf-8");
$mysqli = new mysqli('127.0.0.1','root','root','mysqli');
$mysqli -> query('set names utf8' );
$mysqli -> autocommit(false);//开启事务
$sql = "UPDATE users SET money=money-10 WHERE id=1";
$result = $mysqli -> query($sql);
echo $mysqli -> affected_rows;
var_dump($result);
<?php
header("content-type:text/html;charset=utf-8");
$mysqli = new mysqli('127.0.0.1','root','root','mysqli');
$mysqli -> query('set names utf8' );
$mysqli -> autocommit(false);//开启事务 false为不开启
$sql1 = "UPDATE users SET money=money-10 WHERE id=1";
$sql2 = "UPDATE users SET money=money+10 WHERE id=2";
$result = $mysqli -> query($sql1);
$r1 =  $mysqli -> affected_rows; //受sql语句影响的的条数
$result = $mysqli -> query($sql2);
$r2 =  $mysqli -> affected_rows;
if ($r1>0 && $r2>0){
    $mysqli -> commit();//事务提交
    echo '操作成功';
}else{
    $mysqli -> rollback();//事务回滚
    echo '操作失败';
}
var_dump($result);