1、开启事务方法 startTrans()
2、事务提交方法 commit()
3、事务回滚方法 rollback()
用法例子:
$order = M(‘order’);
$allAdded = true; //先设定一个值为 true;
$data['name'] = 'winter';
$order->startTrans(); //开启事物
for($i = ;$i<;$i++){
$sign = $order->add($data); //添加一条数据到order表
if(!$sign){
$order->rollback(); //如果order添加失败事物回滚
$allAdded = false; //并且把allAdded设置为 false
}
}
//回滚
if($allAdded){
$order->commit();
// 如果allAdded为真则两条数据都成功;那么 commit事物提交
echo '添加成功';
}else{
echo '添加失败';
}
如果commit了。那么就提交插入数据。如果发现alladded为假说明有条数据没插入正确。那么就rollback回滚就会取消事物开启之后操作数据库的所有行为。
提供一个例子助于大家加深理解
public function insertdata(){
$model = M();
$model->startTrans();
$data['name'] = 'winter';
//增加一条用户信息
$si = $model->table(C('DB_PREFIX').'user')->add($data);
if(!$si){
$model->rollback();
exit();
}
$car['brand'] = $si;
//增加一条用户id
$c = $model->table(C('DB_PREFIX').'car')->add($car);
if($si && $c){
$model->commit();
}else{
$model->rollback();
}
}
复制代码
例子二:
//提现操作
public function ajax_tx()
{
//判断是否登录
if(session('uid') == NULL || session('uid') == "" || session('uid') == false) {
echo "300";
exit;
}else{
//接受提现提交来的数据 $txnumber = intval(trim($_POST['txnumber'])); $name = trim($_POST['name']);
$alipay_number = trim($_POST['alipay_number']);
$data = M("fanxian_new")->where("f_uid='".session('uid')."'")->find();
if(empty($txnumber)){
echo "301";exit;//提现金豆不能为空
}else{
if(empty($data) || intval($data['f_fan_fee'])==0){
echo "302";exit;//无可提现金豆
}else{
if($data['f_fan_fee']<number_format($txnumber,2)){
echo "303";exit;//提现金豆数请勿大于持有金豆数
}else{
if(empty($alipay_number)){
echo "304";exit;//提现者支付宝账号不能为空
}
if(empty($name)){
echo "305";exit;//提现者真实姓名不能为空
} $model=new \Think\Model();
$model->startTrans(); //开启事物
//操作提现记录
$fanxian_new_log = M("fanxian_new_log");
$fanxian_new_log->f_num_fee = number_format($txnumber,2);
$fanxian_new_log->f_lmId = session("uid");
$fanxian_new_log->f_create_time = time();
$fanxian_new_log->f_name = $name;
$fanxian_new_log->f_alipay = $alipay_number;
$fanxian_new_log->f_status = 1;//1表示提现记录 0表示返现记录
$jdtx = $fanxian_new_log->add(); $fanxian_new = M("fanxian_new");
$fanxian_new->f_uid = $data['f_uid'];
$fanxian_new->f_fan_fee = $data['f_fan_fee']-number_format($txnumber,2);
$jd = $fanxian_new->save();
if(!empty($jdtx) && !empty($jd)){
//提交
$model->commit();
echo "200";exit;//提现成功
}else{
//回滚
$model->rollback();
echo "306";exit;//提现失败
} }
}
} }
}