0

I am trying to use post_system or post_controller hook to catch and log all insert and update queries in a database table. But, what happens is that the $queries = $CI->db->queries; statement doesn't seem to catch any insert or update statement at all. It only catches SELECT statements even when new data is inserted or old data is updated in respective views/controllers.

Here is my relevant code:

hooks.php

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

// also tried with post_controller hook
$hook['post_system'] = array(
    'class' => 'Db_query_log', 
    'function' => 'log_db_queries', 
    'filename' => 'db_log.php', 
    'filepath' => 'hooks'        
);

hooks/db_log.php

    <?php

class Db_query_log {

    function __construct() {
        //nothing special    
    }

    function log_db_queries() {
        $CI = & get_instance();
        $queries = $CI->db->queries;

        foreach ($queries as $key => $query) {
            echo $query . "<br>"; 
        // all statements displayed are SELECT statements even for UPDATE and INSERT operations performed by controllers where data is actually changed 
        }
    }

}

What could be the culprit here? Am I missing something or this hook simply ignores INSERT/UPDATE operations?

Any help would be appreciated, thanks!

Nadeem Khan
  • 3,408
  • 1
  • 30
  • 41

2 Answers2

0

Use post_controller instead of post_system :

$hook['post_controller'] = array(
    'class' => 'Db_query_log', 
    'function' => 'log_db_queries', 
    'filename' => 'db_log.php', 
    'filepath' => 'hooks'        
);
JC Sama
  • 2,214
  • 1
  • 13
  • 13
0

To achieve this open any helper file and put this code at the bottom

function log_que($sql) {
        $filepath = APPPATH . 'logs/Query-log-' . date('Y-m-d') . '.php';   
            $handle = fopen($filepath, "a+");
            fwrite($handle, $sql." \n Execution Time: ".date("Y-m-d H:i:s")."\n\n");  
            fclose($handle);   
}

after this go to system/database/DB_driver.php and find function named "query" and put this below code on top inside the function.

log_que($sql);'

then all the queries will save in a file inside the application/logs folder.

you can put if condition if you want to save only specific queries. LIKE

if(preg_match('/INSERT/',$sql)) {
 fwrite($handle, $sql." \n Execution Time: ".date("Y-m-d H:i:s")."\n\n");  
}
Noor
  • 45
  • 8