Home > PHP Framework > ThinkPHP > body text

Transaction operations in ThinkPHP5

silencement
Release: 2020-01-30 22:49:41
forward
4723 people have browsed it

Transaction operations in ThinkPHP5

If you use transaction processing, the database engine needs to support transaction processing. For example, MySQL's MyISAM does not support transaction processing and requires the use of the InnoDB engine.

ThinkPHP5.0

Use the transaction method to operate database transactions. When an exception occurs, it will automatically roll back, for example:

Automatically control transactions Handling

Db::transaction(function(){
    Db::table('think_user')->find(1);
    Db::table('think_user')->delete(1);});
Copy after login

You can also manually control transactions, for example:

// 启动事务Db::startTrans();try{
    Db::table('think_user')->find(1);
    Db::table('think_user')->delete(1);
    // 提交事务
    Db::commit();    } catch (\Exception $e) {
    // 回滚事务
    Db::rollback();}
Copy after login

ThinkPHP5.1

The simplest way is to use the transaction method to operate database transactions. When the code in the closure An exception will be automatically rolled back, for example:

Db::transaction(function () {
    Db::table('think_user')->find(1);
    Db::table('think_user')->delete(1);});
Copy after login

You can also manually control the transaction, for example:

// 启动事务Db::startTrans();try {
    Db::table('think_user')->find(1);
    Db::table('think_user')->delete(1);
    // 提交事务
    Db::commit();} catch (\Exception $e) {
    // 回滚事务
    Db::rollback();}
Copy after login

Note that during transaction operations, make sure that your database connection is using the same one.

Starting from version V5.1.13, MySQL’s XA transaction can be supported to implement global (distributed) transactions. You can use:

Db::transactionXa(function () {
    Db::connect('db1')->table('think_user')->delete(1);
    Db::connect('db2')->table('think_user')->delete(1);}, [Db::connect('db1'),Db::connect('db2')]);
Copy after login

Make sure your data table engine is InnoDB, and Enable XA transaction support.

The above is the detailed content of Transaction operations in ThinkPHP5. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:www.liqingbo.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!