How to print SQL statement in codeigniter model

前端 未结 14 1803
迷失自我
迷失自我 2020-11-30 22:08

I have a sql statement in my model,

I then say

$query = $this->db->query($sql, array(fields, fields1);

if ($query) {
    return true:
} else {         


        
相关标签:
14条回答
  • 2020-11-30 22:44

    You can display the ActiveRecord generated SQL:

    Before the query runs:

    $this->db->_compile_select(); 
    

    And after it has run:

    $this->db->last_query(); 
    
    0 讨论(0)
  • 2020-11-30 22:48

    if you need a quick test on your query, this works great for me

    echo $this->db->last_query(); die;
    
    0 讨论(0)
  • 2020-11-30 22:48

    After trying without success to use _compiled_select() or get_compiled_select() I just printed the db object, and you can see the query there in the queries property.

    Try it yourself:

    var_dump( $this->db );
    

    If you know you have only one query, you can print it directly:

    echo $this->db->queries[0];
    
    0 讨论(0)
  • 2020-11-30 22:48

    There is a new public method get_compiled_select that can print the query before running it. _compile_select is now protected therefore can not be used.

    echo $this->db->get_compiled_select(); // before $this->db->get();
    
    0 讨论(0)
  • 2020-11-30 22:52

    You can use this:

    $this->db->last_query();
    

    "Returns the last query that was run (the query string, not the result)."

    Reff: https://www.codeigniter.com/userguide3/database/helpers.html

    0 讨论(0)
  • 2020-11-30 22:54

    I read all answers here, but cannot get

    echo $this->db->get_compiled_select();
    

    to work, It gave me error like,

    Call to protected method CI_DB_active_record::_compile_select() from context 'Welcome'in controllers on line xx

    So i removed protected from the below line from file \system\database\DB_active_rec.php and it worked

    protected function _compile_select($select_override = FALSE)
    
    0 讨论(0)
提交回复
热议问题