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);});
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();}
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);});
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();}
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')]);
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!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)
