当前位置: 移动技术网 > IT编程>开发语言>PHP > Laravel5.* 打印出执行的sql语句的方法

Laravel5.* 打印出执行的sql语句的方法

2017年12月12日  | 移动技术网IT编程  | 我要评论

523au,牧羊犬名字,刀剑神域第二季第二集

本文介绍了laravel5.* 打印出执行的sql语句的方法,分享给大家,具体如下:

打开app\providers\appserviceprovider.php,在boot方法中添加如下内容

5.2以下版本

// 先引入db 
use db;
// 或者直接使用 \db::
 db::listen(function($sql, $bindings, $time) {
        dump($sql);
      });

5.2及以上版本

use db;
// 或者直接使用 \db::
// 只能接受一个参数

queryexecuted {#84 ▼
 +sql: "select * from `posts` where `slug` = ? limit 1"
 +bindings: array:1 [▶]
 +time: 0.59
 +connection: mysqlconnection {#85 ▶}
 +connectionname: "mysql"
}

 db::listen(function($sql) {
        dump($sql);
        // echo $sql->sql;
        // dump($sql->bindings);
      });

// 如果要放入日志文件中
db::listen(
  function ($sql) {
    // $sql is an object with the properties:
    // sql: the query
    // bindings: the sql query variables
    // time: the execution time for the query
    // connectionname: the name of the connection

    // to save the executed queries to file:
    // process the sql and the bindings:
    foreach ($sql->bindings as $i => $binding) {
      if ($binding instanceof \datetime) {
        $sql->bindings[$i] = $binding->format('\'y-m-d h:i:s\'');
      } else {
        if (is_string($binding)) {
          $sql->bindings[$i] = "'$binding'";
        }
      }
    }

    // insert bindings into query
    $query = str_replace(array('%', '?'), array('%%', '%s'), $sql->sql);

    $query = vsprintf($query, $sql->bindings);

    // save the query to file
    $logfile = fopen(
      storage_path('logs' . directory_separator . date('y-m-d') . '_query.log'),
      'a+'
    );
    fwrite($logfile, date('y-m-d h:i:s') . ': ' . $query . php_eol);
    fclose($logfile);
  }
);

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网