Tags
Asked 2 years ago
17 Jun 2021
Views 294
Connie

Connie posted

How to print SQL statement in codeigniter model

How to print SQL statement in codeigniter model
Mahesh Radadiya

Mahesh Radadiya
answered Apr 27 '23 00:00

You can print the SQL statement generated by the Active Record or Query Builder in CodeIgniter by using the $this->db->last_query() method. This method returns the SQL query generated by the most recent query executed.

Here's an example of how you can print the SQL statement in a CodeIgniter model:


class My_model extends CI_Model {

    public function get_data() {
        $this->db->select('*');
        $this->db->from('my_table');
        $this->db->where('id', 1);
        $query = $this->db->get();
        $sql = $this->db->last_query();
        echo $sql;
        return $query->result();
    }
}

In this example, we are defining a model named My_model with a method get_data () that retrieves data from a table named " my_table " where the " id " column equals 1. After executing the query using $this->db->get(), we retrieve the SQL statement generated by the query using $this->db->last_query(). We then print the SQL statement using echo.

Note that you should only use this for debugging or optimization purposes, and not in production code. Printing SQL statements can expose sensitive information, and may impact the performance of your application.
Post Answer