Finding the last database query

Sometimes, it is useful to know about the last query that was run against the database, either for debugging purposes or for reasons where you wish to have an audit trail of every interaction with the database—you'll be surprised at the number of times you'll need to do this. CodeIgniter comes with a really handy function that you can use to write out the most recent query that CodeIgniter sent to the database.

How to do it...

  1. Add or adapt the following line of code into your controller or model:
    $this->db->last_query();

How it works...

Quite simply, this function will return the last query to be sent to the database; you can place it in the controller or model (even the view if you wish, but it's better to keep it at ...

Get CodeIgniter 2 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.