Codeigniter: does $this->db->last_query(); execute a query?

Codeigniter: does $this->db->last_query(); execute a query?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Codeigniter: Does $this->db->last_query() Execute a Query?

In the Active Record pattern used by CodeIgniter, developers often rely on the database driver to manage the lifecycle of SQL statements. A common point of confusion arises when inspecting the raw query string. Specifically, does calling $this->db->last_query() trigger the execution of a pending query, or is it merely a retrieval mechanism?

The answer is definitive: calling $this->db->last_query() does not execute the query. It simply returns the SQL string that was constructed and executed previously. In your specific example, the execution event occurs at the get_where() method call, not when you subsequently access last_query().

When you invoke $this->db->get_where('Contacts', array('id' => $contact_id)), CodeIgniter follows a distinct internal sequence. The framework first builds the SQL string based on your parameters and the current query builder state (in this case, adding the SELECT * clause). Once that string is formed, the driver immediately sends it to the database server via the underlying connection object. This transmission marks the "execution" phase.

Immediately following this execution, the result set—whether a dataset array or an object—is populated and returned. The $this->db->last_query() method acts as a read-only accessor into the internal $query property of the database class. It returns the exact string that was sent to the server. If you attempt to call last_query() before get_where(), you will receive an empty string or the previous query from a different request context, depending on how your application handles state isolation between requests.

Is $this->db->last_query() Reliable?

For debugging purposes, $this->db->last_query() is generally reliable within the scope of a single request cycle. However, it comes with significant caveats regarding timing and scope that developers must respect.

The primary limitation is that the property holding the last query is overwritten immediately after the next database operation occurs. If your controller or model performs multiple queries in sequence:

$this->db->select('*');
$q1 = $this->db->get_where('Contacts', array('id' => $contact_id));
$sql = $this->db->last_query(); // Retrieves Contacts query

$q2 = $this->db->get_where('Users', array('role' => 'admin'));
// The property is now updated to the Users query

echo $sql; // Outputs the Contacts query, not the Users query

In this scenario, $sql still holds the value from the first operation. This behavior is consistent with how most Active Record implementations handle state; they do not maintain a log of every executed statement in memory indefinitely because it consumes unnecessary resources.

Furthermore, relying on last_query() to inspect complex queries built dynamically can be fragile if the database class instance has been reset or if a new query builder object was instantiated separately without merging the state. If you switch from one Query Builder instance to another, the $this->db reference might point to a different context entirely, returning the last query of that specific instance rather than the one you just ran in your current logic flow.

Best Practices for Query Inspection

If you need to log queries or debug SQL execution without altering the application flow, it is better practice to capture the output directly from the result object if available, or ensure you are accessing the property immediately after the execution step.

$q = $this->db->get_where('Contacts', array('id' => $contact_id));

// Capture immediately
$sql = $this->db->last_query();

// Log or process
log_message('debug', 'Executed: ' . $sql);

Avoid storing the result of last_query() in a variable if you intend to perform further database operations before using that string, unless your logic specifically requires inspecting the previous statement. The moment another query runs, the "previous" becomes irrelevant to the current execution context.

For those migrating from legacy CodeIgniter patterns or seeking more robust debugging tools, modern frameworks like Laravel provide extensive logging capabilities in the log_channel configuration, which automatically capture every executed query with bindings and execution time. While CodeIgniter does not offer this out-of-the-box by default, understanding the stateless nature of last_query() is crucial for writing maintainable database logic that doesn't accidentally break when refactoring code blocks.

Our network