Resolved: CodeIgniter4: How to get executed MySQL queries between sending an HTTP request and receiving an HTTP response


  1. Start.
  2. HTTP request.
  3. Execute SQL queries.
  4. HTTP response.

I want to get queries between requests and responses (how many queries and the raw SQL query).
->getLastQuery() only returns 1 last query. I want to save all queries between sending an HTTP request and receiving an HTTP response.

My failed example;

Best Answer:


Try using The Debug Toolbar. The Debug Toolbar provides at-a-glance information about the current page request, including benchmark results, queries you have run, request and response data, and more.
Alternatively, you could tap into the execution of your application by subscribing to the DBQuery event. This can be done by registering with the app/Config/Events.php class to let it know that you want to perform an action when that event is triggered.
Defining an Event

Most events are defined within the app/Config/Events.php file. You can subscribe an action to an event with the Events class’ on() method. The first parameter is the name of the event to subscribe to. The second parameter is a callable that will be run when that event is triggered:

<?php use CodeIgniter\Events\Events; Events::on(‘pre_system’, [‘MyClass’, ‘myFunction’]); In this example, whenever the pre_system event is executed, an instance of MyClass is created and the myFunction() method is run. Note that the second parameter can be any form of callable that PHP recognizes: <?php // Call a standalone function Events::on(‘pre_system’, ‘some_function’); // Call on an instance method $user = new User(); Events::on(‘pre_system’, [$user, ‘someMethod’]); // Call on a static method Events::on(‘pre_system’, ‘SomeClass::someMethod’); // Use a Closure Events::on(‘pre_system’, static function (…$params) { // … });


In your app/Config/Events.php class, subscribe to the DBQuery event.
DBQuery -: Called after a database query whether successful or not. Receives the \CodeIgniter\Database\Query object.Event Points

If you have better answer, please add a comment about this, thank you!