Home > Article > Backend Development > Summary of how to use database transactions in Yii_PHP tutorial
The Yii framework supports database transaction processing. I won’t say much about transactions here. Readers who want to know more can refer to Articles on this site:
About database (MySQL) transactions
Transactions are generally used when batch deletions are encountered in projects. Here is a usage example to share with you.
<?php $array=array( 0=>array('username'=>'phpernote.com_0','password'=>'123456'), 1=>array('username'=>'u_1','password'=>'123456'), 2=>array('username'=>'u_2','password'=>'123456') ); $transaction=Yii::app()->db->dbConnection->beginTransaction(); //此处db代表的是定义在main.php中的数据库连接对象db try{ Yii::app()->db->createCommand()->insert('tbl_user',$array[0]); Yii::app()->db->createCommand()->insert('tbl_user',$array[1]); Yii::app()->db->createCommand()->insert('tbl_user',$array[2]); $transaction->commit(); }catch(Exception $e){ $transaction->rollback(); }
Note: If you are using a MySQL database, the table engine must be of the innodb type. Because the MyISAM engine of the MySQL database does not support transaction processing, the above code will not achieve the expected purpose.