While developing CodeIgniter application, we may need to save or log all SQL queries in order to debug the code or just want to know exactly what happens with MySQL database.
Save Or Log All SQL Queries in CodeIgniter
Below are 3 simple steps need to be implemented before we can record MySQL queries.
1. Enable System Hooks feature – set enable_hooks to TRUE in /application/config/config.php file
/application/config/config.php
1 2 3 4 5 6 7 8 9 10 | /* |-------------------------------------------------------------------------- | Enable/Disable System Hooks |-------------------------------------------------------------------------- | | If you would like to use the 'hooks' feature you must enable it by | setting this variable to TRUE (boolean). See the user guide for details. | */ $config['enable_hooks'] = TRUE; |
2. Define the ‘Hook’ – open the /application/config/hooks.php and add the
following PHP code:
/application/config/hooks.php
1 2 3 4 5 6 | $hook['display_override'][] = array( 'class' => '', 'function' => 'log_queries', 'filename' => 'log_queries.php', 'filepath' => 'hooks' ); |
3. Implement the hook which was defined in step #2 – create a new file named log_queries.php in /application/hooks/ and add following PHP code:
/application/hooks/log_queries.php
1 2 3 4 5 6 7 8 9 10 11 12 | <?php function log_queries() { $CI =& get_instance(); $times = $CI->db->query_times; foreach ($CI->db->queries as $key=>$query) { echo "Query: ". $query." | ".$times[$key] . "<br>"; } $CI->output->_display(); } ?> |
In the log_queries function above, we display all SQL queries on the browser. If you like to write/save them to a log file or even store them all in database, simple revise the foreach loop.