很简单的一个事物回滚,简单介绍下事物回滚,示例怎么使用Thinkphp的回滚。下面上俩个由浅入深的例子。会给你帮助理解,和提升。
//具体的讲解请允许我把它放在了 http://www.ichasem.com/?p=331 这里
1、开启事务方法 startTrans()
2、事务提交方法 commit()
3、事务回滚方法 rollback()
用法例子:$order = M(‘order’);<br>
$allAdded = true; //先设定一个值为 true;<br>
$data['name'] = 'winter';<br>
$order->startTrans(); //开启事物<br>
for($i = 1;$i
$sign = $order->add($data); //添加一条数据到order表<br>
if(!$sign){<br>
$order->rollback(); //如果order添加失败事物回滚<br>
$allAdded = false; //并且把allAdded设置为 false<br>
}<br>
}<br>
<br>
//回滚<br>
if($allAdded){<br>
$order->commit(); <br>
// 如果allAdded为真则两条数据都成功;那么 commit事物提交<br>
echo '添加成功';<br>
}else{<br>
echo '添加失败';<br>
}
小解析:如果commit了。那么就提交插入数据。如果发现alladded为假说明有条数据没插入正确。那么就rollback回滚就会取消事物开启之后操作数据库的所有行为。
winter在提供一个例子助于大家加深理解~public function insertdata(){<br>
$model = M();<br>
$model->startTrans();<br>
$data['name'] = 'winter';<br>
//增加一条用户信息<br>
$si = $model->table(C('DB_PREFIX').'user')->add($data);<br>
if(!$si){<br>
$model->rollback();<br>
exit();<br>
}<br>
$car['brand'] = $si;<br>
//增加一条用户id<br>
<br>
$c = $model->table(C('DB_PREFIX').'car')->add($car);<br>
if($si && $c){<br>
$model->commit();<br>
}else{<br>
$model->rollback();<br>
}<br>
}
AD:真正免费,域名+虚机+企业邮箱=0元

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor