CodeIgniter 4 How to Print or Get Last Executed Query

Reading Time: 4 minutes
901 Views

This post will teach you how to print or get the last run query in CodeIgniter 4 in a very effective and helpful manner. Monitoring and debugging database queries is an important component of optimising efficiency and guaranteeing data accuracy as a CodeIgniter developer.

In this article, we will look at techniques and methods for printing or retrieving the most recently executed query in CodeIgniter 4. Accessing the last executed query provides vital insights into your application’s data interactions, whether you’re debugging database issues, analysing query performance, or simply wondering about the underlying SQL expressions.

Read More: How To Cache Database Query Using CodeIgniter Cache?

Let’s get started.

CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.

Environment (.env) Setup

When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Either we can do via renaming file as simple as that. Also we can do by terminal command.

Open project in terminal

cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
 
CI_ENVIRONMENT = development

Now application is in development mode.

Enable Database Debug Mode

You may also need to enable query debug mode of database.

Open Database.php file from /app/Config folder. Search for your database group. By default in CodeIgniter v4 it will be $default database group.

//...

    /**
     * The default database connection.
     */ 
    public array $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => '',
        'password' => '',
        'database' => '',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => true,
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,
    ];

//...

DBDebug shoud be set to true value.

'DBDebug'  => true,

Read More: Step by Step How To Setup Cron Jobs in CodeIgniter 4 Tutorial

Print Last Executed Database Query

Suppose we have a table called users in database.

We are running an operation to get a user row value by Query builder method on the basis of email value.

Let’s see in action.

<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class SiteController extends BaseController
{
    private $db;
  
    public function __construct(){

        $this->db = db_connect();
    }
  
    public function getMyData()
    {
        $tableObject = $this->db->table("users");

        $data = $tableObject->where([
            "email" => "sanjay@gmail.com"
        ])->get()->getRowArray();

        echo $this->db->getLastQuery();
    }
}

Concept

To print / get last executed query is:

echo $this->db->getLastQuery();

Output will be,

SELECT * FROM `users` WHERE `email` = 'sanjay@gmail.com'

More Learning

If you want to create application logs while doing any operation with database or anything you can also do that in a very easier way. It is by using log_message() helper function.

That’s it.

We hope this article helped you to learn about CodeIgniter 4 How to Print or Get Last Executed Query Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.