Skip to main content

Get last executed query in codeigniter

You can get the last executed query in Codeigniter by simply using the last_query() function of the db class in Codeigniter 3, and the getLastQuery() method on the database connection class in Codeigniter 4.

  • Get last executed query in codeigniter 3

    --PATH app\Controllers\<Home>.php
    public function index()
    {
        $data['data'] = $this->db->get("users")->result();
        $executedQuery = $this->db->last_query();
        print_r($executedQuery);
        exit;
    }
    
    SELECT * FROM `users`

    You can get the last executed query in codeigniter 3 by calling the last_query() method on db class. You have to use the get() method on the users table to execute a query which we want to get and after that call last_query() method on db class to get the last executed query in Codeigniter 3.

  • Get last executed query in codeigniter 4

    public function index()
    {
        $db = \Config\Database::connect();
        $heroesCount = $db->table('heroes')->countAll();
        echo $db->getLastQuery();
        exit;
    }
    

    //Output

    SELECT COUNT(*) AS `numrows` FROM `heroes`

    You can easily get the last executed query in Codeigniter 4 using the getLastQuery() method on the \Config\Database::connect(). This method returns the raw SQL query string, not the result. 

  • Back to code snippet queries related codeIgniter