Get last executed query in codeigniter

Created at 14-May-2021 , By samar

Get last executed query in codeigniter

With this article, we’ll look at some examples of how to address the "Get last executed query in codeigniter" problem.

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

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.