Home  >  Article  >  PHP Framework  >  ThinkPHP database operation query events, transaction operations, monitoring SQL

ThinkPHP database operation query events, transaction operations, monitoring SQL

藏色散人
藏色散人forward
2021-02-01 11:01:062858browse

The following tutorial column will introduce you to the query events, transaction operations, and monitoring SQL of ThinkPHP database operations. I hope it will be helpful to friends in need!

Query Event

##Query Event (V5.0.4)

Starting from version 5.0.4, support for CURD operation events of the database has been added, including:

Query events are only supported find, select, insert, update and delete methods.

Register events

Use the following method to register database query events

Query::event('after_insert','callback');
Query::event('before_select',function($options,$query){    // 事件处理
    return $result;
});

Transaction operation

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. Use the transaction method to operate database transactions. When an exception occurs, it will automatically roll back, for example:

Automatically control transaction processing

Db::transaction(function(){
    Db::table('think_user')->find(1);
    Db::table('think_user')->delete(1);
});
Manual control of transactions

// 启动事务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, ensure that your database The connection is the same.

Listen to SQL

If you turn on the debugging mode of the database, you can execute any command on the database. To monitor SQL operations, use the following method:

Db::listen(function($sql, $time, $explain){    // 记录SQL
    echo $sql. ' ['.$time.'s]';    // 查看性能分析结果
    dump($explain);
});
 By default, if no monitoring operations are registered, these SQL executions will be recorded in the log according to different log types.

The above is the detailed content of ThinkPHP database operation query events, transaction operations, monitoring SQL. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete