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 Autostart GlassFish Server on Ubuntu Startup

Learn how to configure GlassFish Server to start automatically on system boot in Ubuntu. Step-by-step guide using systemd service scripts.

If you want GlassFish Server to launch automatically when your Ubuntu system boots, you can easily achieve that by creating an init script. This allows you to manage GlassFish’s start, stop, and restart actions seamlessly.

In this article, we learn to create the init script for GlassFish server and how to configure it in Ubuntu systems to control GlassFish server.

Step 1: Create the Init Script

The init script file for GlassFish Server is to be created at /etc/init.d/.

For managing all GlassFish Server startup events, it ships with the asadmin tool. Use this tool in the startup script as follows,

Create GlassFish init file using the following command:

sudo nano /etc/init.d/glassfish

Paste the following lines in the file

#!/bin/sh
# Prevent potential issues by defining Java path
export AS_JAVA=/usr/lib/jvm/jdk1.8.0
GLASSFISHPATH=/home/glassfish/bin

case "$1" in
  start)
    echo "Starting GlassFish from $GLASSFISHPATH"
    sudo -u glassfish $GLASSFISHPATH/asadmin start-domain domain1
    ;;
  stop)
    echo "Stopping GlassFish from $GLASSFISHPATH"
    sudo -u glassfish $GLASSFISHPATH/asadmin stop-domain domain1
    ;;
  restart)
    $0 stop
    $0 start
    ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 3
    ;;
esac

This script uses asadmin to control the domain named domain1, running it as a dedicated glassfish user for security and proper permissions.

Step 2: Make the Script Executable

Now, glassfish startup script is created. We need to add this file in startup to make Glassfish Server autostart during Ubuntu startup.

Set the appropriate permissions so the system can run it at boot:

sudo chmod a+x /etc/init.d/glassfish

Step 3: Register the Script to Run at Startup

Link it into Ubuntu’s init system to execute during startup:

sudo update-rc.d glassfish defaults

This ensures the script will be triggered automatically during system boot.

Step 4: Validate the Setup

Now, restart Ubuntu and check if it really autostart the Glassfish Server.

Step 5: Validate Manual Commands

You can also manage Glassfish Server startup events as follows,

sudo /etc/init.d/glassfish start  # Start the server
sudo /etc/init.d/glassfish stop   # Stop the server
sudo /etc/init.d/glassfish restart  # Restart the server

Conclusion

Setting up GlassFish to start automatically on boot ensures that your applications and services are always available after a system reboot—without requiring manual intervention. By creating a simple init script and registering it with Ubuntu’s startup sequence, you can streamline your server management and reduce downtime. This method is especially useful for production environments where stability and automation are critical.

If you’re using a newer Ubuntu version that defaults to systemd, consider switching to a systemd service file for even better control and logging.

Access shell with SSH on cPanel server from Linux

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.

Some of the important server related problems will be solved only using shell access to the server. To access the cPanel server shell using SSH, there must be an SSH client installed on PC. Most of the Linux distros include SSH client software by default. If it is not installed, then it can be easily installed with following commands,

For Ubuntu: apt-get install openssh-client
For CentOS: yum install openssh-clients

After installation, follow these steps to access the cPanel shell with SSH from Linux:

  1. Login to cPanel and go to Security > SSH/Shell Access to generate SSH key pair.
  2. Click Manage SSH Keys > Generate a New Key. You should use a password to protect the key. You will be asked the password each time you use the key.
  3. In Public Keys section click ‘Manage Authorization’ and ‘Authorize’
  4. In Private Keys section click, Vew/Download then download the key (id_dsa or id_rsa) to your PC.
  5. Save it to ~/.ssh directory on your Linux machine under a meaningful name to not overwrite your existing keys for example id_dsa.myjavahost
  6. Now make sure permissions are correct on the key (one-time task) and connect:
    mypc:~$ chmod 600 .ssh/id_dsa
    mypc:~$ ssh -p1033 -i .ssh/id_dsa yourusername@yourservername
    Enter passphrase for key '.ssh/id_dsa':
  1. Provide the password for the key, set up in step #2

You should be logged in by now.

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 Display Facebook Albums and Photos on Your Website

Easily embed Facebook photo albums and images on your website using Graph API or plugins. Step-by-step guide to showcase Facebook content seamlessly.

Facebook Album Browser is a Reponsive jQuery plugin for browsing public albums and photos from any Facebook account and showcases them as a photo gallery on your website. Albums are displayed with respective cover photos. Click on the cover photo to display all the photos under the album. Click on any photo opens the lightbox with next/prev buttons to navigate.

The main purpose of this plugin is to embed and customize Facebook photo albums in your website without being limited with Facebook styling. It also allows you to use it as picker as it raises events for clicked album/photo.

Plugin is compatible for both desktop and mobile websites.

How to Use:

  1. Load Facebook Album Browser plugin right after the jQuery library as shown below.
    <link rel="stylesheet" href="src/jquery.fb.albumbrowser.css">
    <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
    <script src="src/jquery.fb.albumbrowser.js"></script>

  2.  Create a container element in body of the page to display the Facebook Album Browser.
    <div class="fb-album-browser"></div>

  3. Call Facebook Album Browser in above container element and provide Facebook account to display albums as below.
    $(document).ready(function () {
    $(".fb-album-browser").FacebookAlbumBrowser({
    account: "starsportsindia"
    });
    });

  4. Use other options listed below to customize Facebook Album Browser plugin.
    // Facebook account
    account: "",

    // Facebook access token
    accessToken: "",

    // Display account information
    showAccountInfo: true,

    // Display the number of images
    showImageCount: true,

    // Skip albums which have no images
    skipEmptyAlbums: true,

    // An array of albums to be skipped
    skipAlbums: [],

    // switching on/off lightbox
    lightbox: true,

    // Allows using of plugin as an image multipicker.
    photosCheckbox: true,

    // An array of photos to be checked
    checkedPhotos: [],

  5. Use events listed below to perform specific actions on specific user action.
    // when album is selected in the browser.
    albumSelected: null,

    // when photo is selecetd in the browser.
    photoSelected: null,

    // when photo is selecetd in the browser.
    photoChecked: null,

    // when photo is checked.
    photoUnchecked: null,

  6. Every event function returns an object with following properties:
    id: image id in Facebook database
    url: large image url
    thumb: thumbnail image url
     

Download: https://github.com/dejanstojanovic/Facebook-Album-Browser