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!

Best Alternative to Set a PostgreSQL Schema Using PHP PDO

Discover an effective way to set PostgreSQL schemas using PHP PDO when the SET search_path approach fails. Learn best practices for schema-based architecture.

To set the PostgreSQL DB connection, schema parameter is not to be included

$Conn = new PDO('pgsql:host=localhost;port=5432;dbname=db', 'user', 'pass');
$result = $Conn->exec('SET search_path TO accountschema');
if ( ! $result) {
die('Failed to set schema: ' . $Conn->errorMsg());
}

Is this a good practice? Is there a better way to do this?

In order to specify the default schema you should set the search_path instead.

$Conn->exec('SET search_path TO accountschema');

You can also set the default search_path per database user and in that case the above statement becomes redundant.

ALTER USER user SET search_path TO accountschema;

Alternative of PHP_Excel for Excel Reading and Writing

For Writing Excel

For Reading Excel

For Reading and Writing Excel

  • Ilia Alshanetsky’s Excel extension now on github (xls and xlsx, and requires business libXL segment)
  • spout OfficeOpenXML (xlsx) and CSV
  • PHP’s COM extension (requires a COM empowered spreadsheet program, for example, MS Excel or OpenOffice Calc running on the server)
  • SimpleExcel Claims to read and compose MS Excel XML/CSV/TSV/HTML/JSON/and so forth arranges

Another C++ Excel expansion for PHP, however you’ll have to manufacture it yourself, and the docs are really meager with regards to attempting to discover what usefulness (I can’t discover from the site what groups it bolsters, or whether it peruses or composes or both…. I’m speculating both) it offers is phpexcellib from SIMITGROUP.

All case to be quicker than PHPExcel from codeplex or from github, however (except for COM, PUNO Ilia’s wrapper around libXl and spout) they don’t offer both perusing and composing, or both xls and xlsx; might never again be upheld; and (while I haven’t tried Ilia’s expansion) just COM and PUNO offers the same level of control over the made exercise manual.

Source: http://stackoverflow.com/questions/3930975/alternative-for-php-excel

How to Get Response Headers Using file_get_contents in PHP

Learn how to retrieve HTTP response headers using file_get_contents in PHP. A practical guide with examples for handling headers efficiently.

file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.

A URL can be used as a filename with this function if the fopen wrappers have been enabled.

But, reading URL becomes difficult to identify that URL is not available. And if URL is not available, it’s also difficult to process that URL. So, it is necessary that there is a response for every request fired by file_get_contents() for any URL.

PHP has a predefined variable named $http_response_header, which provides a response header for any HTTP request sent by PHP code.

For Example,

file_get_contents("http://example.com");
var_dump($http_response_header);

The above example will output something similar to:

array(9) {
  [0]=>
  string(15) "HTTP/1.1 200 OK"
  [1]=>
  string(35) "Date: Sat, 12 Apr 2008 17:30:38 GMT"
  [2]=>
  string(29) "Server: Apache/2.2.3 (CentOS)"
  [3]=>
  string(44) "Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT"
  [4]=>
  string(27) "ETag: "280100-1b6-80bfd280""
  [5]=>
  string(20) "Accept-Ranges: bytes"
  [6]=>
  string(19) "Content-Length: 438"
  [7]=>
  string(17) "Connection: close"
  [8]=>
  string(38) "Content-Type: text/html; charset=UTF-8"
}

Note that the HTTP wrapper has a hard limit of 1024 characters for the header lines.
Any HTTP header received that is longer than this will be ignored and won’t appear in $http_response_header.

The cURL extension doesn’t have this limit.