Programming

How to get the last executed query in PHP Codeigniter? [Solved]

Last query in Codeigniter: Codeigniter provides many database helper functions to deal with the database to get the job done.

Functions to get the last query in CodeIgniter

In this post, we will see details explanations on Codeigniter to get the last query in Codeigniter 3 and CodeIgniter 4

Codeigniter 3 and 4 are having different functions to get the last query in Codeigniter. we will see both of the functions as follows with examples.

Get the last executed query in Codeigniter 3

You can get the last query in Codeigniter 3 by using the following DB class functions

public function get_last_query()
{
  	// quering the orders table
    $users = $this->db->get("orders")->result();
  
  	// get the last query executed
    $last_query = $this->db->last_query();
  
  	// print the $last_query to the screen and exit
    echo "<pre>";
    print_r($last_query);    
    exit;
}

Result: select * from `orders`

You need to first execute the query by calling $this->db->get() db class method. After that, you have to get the last executed query by calling $this->db->last_query() db class method, this will return the raw SQL query string in Codeigniter 3.

Get the last executed query in Codeigniter 4

You can get the last query in Codeigniter 4 very easily using the following DB class functions

public function get_last_query()
{
  	// loading the query builder
  	$db = \Config\Database::connect();
  
  	// quering the orders table
    $users = $db->table("orders")->get();
  
  	// get the last query executed
    $last_query = $db->getLastQuery();
  
  	// print the $last_query to the screen and exit
    echo "<pre>";
    print_r($last_query);    
    exit;
}

Result: select * from `orders`

In Codeigniter 4 , first you need to execute the query by calling $db->table(“”)->get() db class method. After that, you can get the last executed query by calling $db->getLastQuery() db class method on \Config\Database::connect() , this will return the raw SQL query string.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button