Get Last Executed Query in CodeIgniter PHP

Learn how to retrieve the last executed query in CodeIgniter’s built-in query methods developed in PHP. Helpful for debugging and query optimization.

When developing applications with CodeIgniter, retrieving the last executed SQL query becomes the most useful features for debugging and performance tuning. Whether you’re trying to diagnose a bug, optimize performance, or log queries for later review, CodeIgniter makes it easy to access the most recent database query.

In this article, we’ll explore how to get the last executed query in both CodeIgniter 3 and CodeIgniter 4, with examples.

Why Retrieve the Last Executed Query?

Here are a few scenarios where getting the last executed query is helpful:

  • Debugging incorrect or unexpected results.
  • Profiling SQL performance issues.
  • Logging queries for auditing purposes.
  • Building custom query logs for admin or developer panels.

CodeIgniter 3: Getting the Last Query

CodeIgniter 3 provides a simple method from the database class:

$this->db->last_query();

For Example:

public function getUser($id)
{
    $query = $this->db->get_where('users', ['id' => $id]);
    echo $this->db->last_query(); // Outputs the SQL query
    return $query->row();
}

Output:

SELECT * FROM `users` WHERE `id` = '1'

You can also store it in a variable to use it for logging:

$last_query = $this->db->last_query();
log_message('debug', 'Last Query: ' . $last_query);

CodeIgniter 4: Getting the Last Query

In CodeIgniter 4, the approach is slightly different. You can use the getLastQuery() method from the Query Builder object.

Example:

$db = \Config\Database::connect();
$builder = $db->table('users');

$query = $builder->where('id', 1)->get();
echo $db->getLastQuery(); // Outputs the last SQL query

Output:

SELECT * FROM `users` WHERE `id` = 1

getLastQuery() returns a CodeIgniter\Database\Query object, so you can also format it if needed:

echo $db->getLastQuery()->getQuery(); // returns query string

Pro Tips

  • Use this feature only in development mode or behind admin-only views.
  • Avoid exposing raw SQL queries in production environments for security reasons.
  • Combine it with CodeIgniter\Debug\Toolbar for enhanced SQL visibility in CI4.

Logging All Queries in CodeIgniter

You can also log all database queries automatically:

CodeIgniter 3:

In application/config/database.php, set:

$db['default']['save_queries'] = TRUE;

Then access them:

print_r($this->db->queries); // array of all executed queries

CodeIgniter 4:

Use the Debug Toolbar, or manually:

$db = \Config\Database::connect();
$queries = $db->getQueries(); //returns an array of all queries

Conclusion

Accessing the last executed SQL query in CodeIgniter is a powerful feature that can significantly speed up debugging and development. Whether you’re using CodeIgniter 3 or 4, the framework provides convenient tools to track your database interactions.

Make sure to leverage this feature wisely, especially when you’re optimizing queries or tracking down elusive bugs.

Do you use query logging in your CodeIgniter project? Share your tips or challenges in the comments below!

How to Compare Two MySQL Databases Using MySQL Workbench

Learn how to find differences between two MySQL databases using MySQL Workbench. Step-by-step guide to database schema and data comparison.

As a DB Manager, there is always a need for database synchronization or difference tool to upload the latest changes to the server.

For uploading latest files, there are so many tools freely available like SVN. But when there is a time to upload the database changes, there are very few options available for free. MySQL Workbench is one of the free tools provided by Oracle which provides database synchronization as well as database difference facility.

MySQL Workbench is one of the best tools to manage databases. You can connect multiple databases and query each database separately. And most importantly, it also synchronizes and find difference of online as well as offline database. In both cases, you have to manage models of offline database.

It is a unified visual tool which provides data modeling, SQL development, and comprehensive administration tools for server configuration, user administration, and much more. MySQL Workbench is available for free on Windows, Linux and Mac OS.

MySQL Workbench is used to visually design, model, generate, and manage databases, which includes creating complex ER models, forward and reverse engineering. It also delivers visual tools for creating, executing, and optimizing SQL queries. SQL editor of MySQL Workbench provides color.

MySQL Workbench also delivers key features like performing difficult change management and documentation tasks, which normally requires much time and effort.

New version of MySQL Workbench also provide database migration from popular database servers to MySQL, which includes Microsoft SQL Server, Sybase ASE, PostreSQL, and other RDBMS. It’s easy to use solution for migrating can migrate tables, objects and data to MySQL to quickly and easily convert existing applications to run on windows and other platforms.

For more information about MySQL Workbench, visit http://www.mysql.com/products/workbench/
MySQL Workbench is freely available at http://www.mysql.com/downloads/workbench/.