Home > PHP Framework > ThinkPHP > body text

ThinkPHP database operation query events, transaction operations, monitoring SQL

藏色散人
Release: 2021-02-03 18:49:06
forward
2865 people have browsed it

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;
});
Copy after login

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);
});
Copy after login
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();
}
Copy after login
 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);
});
Copy after login
 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!

Related labels:
source:cnblogs.com
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