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 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 Change File Upload Size in Ubuntu via php.ini

Learn how to increase the file upload limit on Ubuntu by editing the php.ini file. Follow this easy guide to update post_max_size and upload_max_filesize.

On Ubuntu server, maximal file size upload limit in php scripts is set to 2Mb as default.  There may be different filesize updated later in php.ini which is not sufficient to upload large database backup in phpMyAdmin.

In order to change that, two things are important,

  • Current upload_max_filesize value
  • Current location of php.ini file

To find current upload_max_filesize value, create a file called ‘pinfo.php’ at your webserver root folder with following content:

phpinfo();

Now, open recently created file in browser via http://localhost/pinfo.php (replace localhost with the servername if necessary) and look for the line

upload_max_filesize 2M

which will show you the actual maximum file size.

To change the upload_max_filesize value, open php.ini file from the location provided in information displayed from pinfo.php file. If php.ini file location is/etc/php5/apache2/php.ini, then open a ssh connection to your server and edit the file /etc/php5/apache2/php.ini as follows

sudo nano /etc/php5/apache2/php.ini

search for “upload_max_filesize” with Ctrl-W and change “2M” to “20M”. Save the file with Ctrl-O and exit with Ctrl-X. Restart the apache server with

sudo /etc/init.d/apache2 restart

and visit again http://localhost/info.php to check if the maximum file size was changed.

There is another way to change upload_max_filesize value for specific project or website only.

If you enabled mod_rewrite you can also put this to your .htaccess file:

php_value upload_max_filesize = 16G
php_value post_max_size = 16G

So, upload_max_filesize value in php.ini file can be changed using .htaccess for project specific and from php.ini file itself for whole server specific.

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 simple and lightweight alternative to cURL for inspecting headers.

When working with APIs or external resources in PHP, sometimes you need to inspect the HTTP response headers — not just the content. While cURL is commonly used for this, you can also retrieve headers using the built-in file_get_contents() function with the right stream context.

In this post, we learn the effective way to get response headers, while using PHP file_get_contents() function.

Using $http_response_header PHP variable to Get Response Headers

We use file_get_contents() to fetch the content from a URL. But with some configuration, you can also access the response headers.

Here’s how you can do it:

<?php
$url = "https://example.com";

// Create a stream context
$options = [
    "http" => [
        "method" => "GET",
        "header" => "User-Agent: PHP\r\n"
    ]
];
$context = stream_context_create($options);

// Fetch the content
$response = file_get_contents($url, false, $context);

// Display the content
echo $response;

// Get the response headers
print_r($http_response_header);
?>

Explanation

  • We used stream_context_create() to define HTTP request options, like headers or methods.
  • The $http_response_header is a special PHP variable automatically populated when using file_get_contents() with an HTTP context.
  • It contains the raw headers returned by the server as an indexed array.

Example Output

When you run the above script, $http_response_header might contain something like:

Array
(
    [0] => HTTP/1.1 200 OK
    [1] => Content-Type: text/html; charset=UTF-8
    [2] => Date: Wed, 25 Jun 2025 10:30:00 GMT
    ...
)

Checking Specific Headers

You can loop through the headers to extract specific values:

foreach ($http_response_header as $header) {
    if (stripos($header, "Content-Type:") !== false) {
        echo "Content-Type Header: $header";
    }
}

Use Cases

We can use this method for various purpose as follows:

  • Verifying HTTP status codes
  • Checking content type or caching headers
  • Basic debugging of server responses without using cURL

Conclusion

While file_get_contents() is often seen as a simple way to read data from URLs, it’s surprisingly powerful when paired with stream contexts. For lightweight HTTP requests where you don’t need advanced control, it’s a quick alternative to cURL — and retrieving headers is straightforward using $http_response_header.

How to Find YouTube Video ID from Any YouTube URL

Learn how to extract the YouTube video ID from different types of YouTube URLs using simple methods and regex examples. Ideal for developers and marketers.

YouTube has so many types of URLs to embed the video on your site. Sometimes it’s difficult to find a single regular expression to parse all type of YouTube URL and retrieve the video ID from it.

To retrieve the video ID from the YouTube URL, use this function,

function getVideoID($url) {
    $pattern = '#^(?:https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch\?v=|/watch\?.+&v=))([\w-]{11})(?:.+)?$#x';
    preg_match($pattern, $url, $matches);
    return (isset($matches[1])) ? $matches[1] : false;
}

Regular Expression explanation is as follows,

$pattern = '#^(?:https?://)?';    # Either http or https.
$pattern .= '(?:www\.)?';         #  Optional, www subdomain.
$pattern .= '(?:';                #  Group host alternatives:
$pattern .=   'youtu\.be/';       #    Either youtu.be,
$pattern .=   '|youtube\.com';    #    or youtube.com
$pattern .=   '(?:';              #    Group path alternatives:
$pattern .=     '/embed/';        #      Either /embed/,
$pattern .=     '|/v/';           #      or /v/,
$pattern .=     '|/watch\?v=';    #      or /watch?v=,    
$pattern .=     '|/watch\?.+&v='; #      or /watch?other_param&v=
$pattern .=   ')';                #    End path alternatives.
$pattern .= ')';                  #  End host alternatives.
$pattern .= '([\w-]{11})';        # Youtube video ids with standard length of 11 chars.
$pattern .= '(?:.+)?$#x';         # Optional other ending URL parameters.

SPF Records for Outgoing Email: What They Are & Why They Matter

Learn what an SPF record is, why it’s essential for email deliverability, and how to configure it properly for sending outgoing emails from your domain.

When users mark messages as spam from a domain, mailbox providers can accurately identify that domain as a potential source of spam – if it has a valid SPF (Sender Policy Framework) records. SPF helps distinguish legitimate senders from spoofed ones. Conversely, if spoofed emails are flagged, SPF enables providers to maintain the domain’s reputation and ensure legitimate mail flows smoothly. Clearly, using SPF helps enhance the accuracy of spam filtering and protect email reputation.

Understand Why SPF Records Often Fails with PHP’s mail()

PHP developers frequently rely on the mail() function for sending emails. However, this approach skips SMTP authentication, making outgoing emails prone to being caught by SPF checks. What’s more, SPF only evaluates the envelope sender (the “Return-Path” header), not the “From” address users actually see. You can read about this at http://www.openspf.org/FAQ/Envelope_from_scope.

In many cases, the envelope sender defaults to the server or localhost, even when the “From” header appears to come from your domain. SPF checks then focus on the envelope sender—if it lacks a proper SPF records, the email may result in a soft fail. Gmail, for instance, might label this as a “best guess record,” which can be incorrect and hurt deliverability.

How to Fix SPF Records Soft-Fail Issues

Here are two effective solutions:

Switch to an SMTP-based mailer

Use libraries like PHPMailer to send emails via SMTP. This allows setting the envelope sender to match the “From” address, enabling proper SPF alignment.

Use sendmail parameters with PHP’s mail()

If refactoring the code is too extensive, you can still adjust the envelope sender using PHP’s mail() function with the -f or -F options in the additional parameters, for example:

mail("user@example.com",  "test subject",  "test message",  $headers,  "-F 'Example  Envelope-sender' -f returnpath@example.com");

This ensures the envelope sender matches your domain – making SPF checks pass correctly.

Conclusion

In essence, SPF plays a vital role in email deliverability and domain reputation. But to leverage it effectively, you must ensure emails send with the correct envelope sender. For PHP developers, the most reliable approach is using SMTP-based mailing; alternatively, configuring the envelope address via sendmail parameters can help bridge the gap without major code changes.