How to print SQL statement in codeigniter model
Asked Answered
C

17

130

I have a sql statement in my model,

I then say

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

if ($query) {
    return true:
} else {
    echo "failed";
    return false;
}

My query always fails, how do I get php to print the exact sql statement being sent to my database? And display that on my php view, page

Cordless answered 26/5, 2011 at 16:43 Comment(0)
B
164

To display the query string:

print_r($this->db->last_query());    

To display the query result:

print_r($query);

The Profiler Class will display benchmark results, queries you have run, and $_POST data at the bottom of your pages. To enable the profiler place the following line anywhere within your Controller methods:

$this->output->enable_profiler(TRUE);

Profiling user guide: https://www.codeigniter.com/user_guide/general/profiling.html

Bullpup answered 26/5, 2011 at 16:49 Comment(6)
when i do print_r($query); nothing prints out at allCordless
Use the CI built in profiler, more info hereBullpup
all i want to do is print out the sql statement as passed to the database, sory but the profiler isn't helping much neitherCordless
Visit the user guide link I posted, if it is not working, tell us what happens instead.Bullpup
well i figured my problem, oracle isn't accepting my date format, ive tried every format i think, it will only accept SYSDATECordless
This seems to output the result of the query, rather than the query itself.Quintanilla
M
242

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

Moncear answered 27/5, 2011 at 11:59 Comment(0)
B
164

To display the query string:

print_r($this->db->last_query());    

To display the query result:

print_r($query);

The Profiler Class will display benchmark results, queries you have run, and $_POST data at the bottom of your pages. To enable the profiler place the following line anywhere within your Controller methods:

$this->output->enable_profiler(TRUE);

Profiling user guide: https://www.codeigniter.com/user_guide/general/profiling.html

Bullpup answered 26/5, 2011 at 16:49 Comment(6)
when i do print_r($query); nothing prints out at allCordless
Use the CI built in profiler, more info hereBullpup
all i want to do is print out the sql statement as passed to the database, sory but the profiler isn't helping much neitherCordless
Visit the user guide link I posted, if it is not working, tell us what happens instead.Bullpup
well i figured my problem, oracle isn't accepting my date format, ive tried every format i think, it will only accept SYSDATECordless
This seems to output the result of the query, rather than the query itself.Quintanilla
I
42

You can display the ActiveRecord generated SQL:

Before the query runs:

$this->db->_compile_select(); 

And after it has run:

$this->db->last_query(); 
Indulgence answered 26/5, 2011 at 21:2 Comment(3)
when i use $this->db->_compile_select(); i get Fatal error: Call to protected method CI_DB_active_record::_compile_select() fromDarcee
The profiler thing is no good for me, does not show the query I want, its over complicated to just get the SQL... This works for me:- echo $this->EE->db->_compile_select();Antichrist
In CI3, Use $this->db->get_compiled_select() instead.Lorient
B
17

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

echo $this->db->last_query(); die;
Bibcock answered 13/1, 2016 at 14:5 Comment(0)
S
14

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();
Southerly answered 16/5, 2013 at 6:22 Comment(1)
Fatal error: Call to undefined method CI_DB_mysql_driver::get_compiled_select()Pinsk
S
14

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];
Squeteague answered 2/4, 2014 at 19:26 Comment(0)
Q
9

You can simply use this at the end..

echo $this->db->last_query();
Quincy answered 1/8, 2015 at 10:10 Comment(0)
O
4

In CodeIgniter4, you do this:

$db = \Config\Database::connect();  
// your queries here
$query = $db->getLastQuery();
$sql = $query->getQuery();
echo $sql;
Oestrone answered 14/6, 2021 at 1:35 Comment(0)
A
2

Neither last_query() or get_compiled_select() works for me, so a slight change of pedro's code works for me just fine. Do not include ->get() in your build, this must be before the ->get()

 echo $this->EE->db->_compile_select();
Antichrist answered 7/10, 2013 at 13:34 Comment(0)
P
2

Add this line right after the query you want to print.

Example:

$query = $this->db->query('SELECT * FROM table WHERE condition');

//Add this line.

var_dump($this->db->last_query());

exit();

or

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

Perak answered 7/11, 2018 at 3:10 Comment(0)
B
1

I try to @Chumillas's answer and @chhameed's answer, but it not work,because the sql is wrong.So I found new approach,like this:

  • Insert echo $sql; flush(); exit; into before return $sql; _compile_select function of DB_active_rec.php
Blazonry answered 26/10, 2013 at 14:42 Comment(0)
E
1

use get_compiled_select() to retrieve query instead of replace it

Elly answered 26/1, 2018 at 11:18 Comment(1)
I'd suggest to show how to use the function you propose in this particular case, not just mention it. Best regardsMalaguena
A
1

In codeigniter 4 I use below code to echo the query. This comes handy especially to see incorrect database queries

use CodeIgniter\Events\Events; 

// listen to the event before $builder->get() or $model->find()

Events::on('DBQuery', function($query){
    log_message('info', $query);
});

This event is triggered whenever a new query has been run, whether successful or not.

Refer official doc on DBQuery Event here.

Arnone answered 1/3, 2023 at 7:52 Comment(1)
should be declared before running CodeIgniter\Model queryArnone
F
0

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)
Faze answered 24/6, 2015 at 10:7 Comment(0)
S
0

I'm using xdebug for watch this values in VSCode with the respective extension and CI v2.x. I add the expresion $this->db->last_query() in the watch section, and I add xdebugSettings node like these lines for get non truncate value in the launch.json.

{
  "name": "Launch currently open script",
  "type": "php",
  "request": "launch",
  "program": "${file}",
  "cwd": "${fileDirname}",
  "port": 9000,
  "xdebugSettings": {
    "max_data": -1,
    "max_children": -1
  }
},

And run my debuger with the breakpoint and finally just select my expresion and do click right > copy value.

Submerge answered 15/2, 2020 at 9:21 Comment(0)
P
0

$query->getCompiledSelect() worked for me.

You can check system\Database\BaseBuilder.php and see which function returns sql query as string. Found this in there and it worked for me.

 /**
     * Get SELECT query string
     *
     * Compiles a SELECT query string and returns the sql.
     *
     * @param boolean $reset TRUE: resets QB values; FALSE: leave QB values alone
     *
     * @return string
     */
    public function getCompiledSelect(bool $reset = true): string
    {
        $select = $this->compileSelect();
    
        if ($reset === true)
        {
            $this->resetSelect();
        }
    
        return $this->compileFinalQuery($select);
    }

and in system\Database\Query.php there is getQuery(). Either of this might be useful.

/**
     * Returns the final, processed query string after binding, etal
     * has been performed.
     *
     * @return string
     */
    public function getQuery(): string
    {
        if (empty($this->finalQueryString))
        {
            $this->finalQueryString = $this->originalQueryString;
        }

        $this->compileBinds();

        return $this->finalQueryString;
    }
Pupil answered 7/11, 2023 at 6:17 Comment(0)
A
-2

I had exactly the same problem and found the solution eventually. My query runs like:

$result = mysqli_query($link,'SELECT * FROM clients WHERE ' . $sql_where . ' AND ' . $sql_where2 . ' ORDER BY acconame ASC ');

In order to display the sql command, all I had to do was to create a variable ($resultstring) with the exact same content as my query and then echo it, like this:<?php echo $resultstring = 'SELECT * FROM clients WHERE ' . $sql_where . ' AND ' . $sql_where2 . ' ORDER BY acconame ASC '; ?>

It works!

Aylesbury answered 15/3, 2016 at 9:43 Comment(1)
This is not the CodeIgniter way.Scatology

© 2022 - 2024 — McMap. All rights reserved.