PHP mysqli学习(六)事物

autocommit(0) 关闭事务自动提交

commit() 提交

rollback() 回滚

 

<?php
header('content-type:text/html;charset=utf-8');
$mysqli = @new mysqli('localhost:3306', 'root', 'root', 'zhy');
if ($mysqli->connect_errno) {
    die('mysqli connect error : ' . $mysqli->connect_error);
}
$mysqli->set_charset('utf8');

$mysqli->autocommit(FALSE);

$sql_add = 'update account set money = money + 100 WHERE username = "user1"';
$sql_reduce = 'update account set money = money - 100 WHERE username = "user2"';

$res_add = $mysqli->query($sql_add);
$rows_add = $mysqli->affected_rows;
$res_reduce = $mysqli->query($sql_reduce);
$rows_reduce = $mysqli->affected_rows;

if($res_add && $res_reduce && $rows_add>0 && $rows_reduce>0){
    $mysqli->commit();
    echo '转账成功<br/>';
    $mysqli->autocommit(TRUE);
}else{
    $mysqli->rollback();
    echo '转账失败<br/>';
}

$mysqli->close();

 

posted @ 2016-05-09 08:58  皎如飞镜临丹阙  阅读(150)  评论(0编辑  收藏  举报