Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print SQL statement in codeigniter model

People also ask

How to print sql query in CodeIgniter?

Use the below query to display the query string: print_r($this->db->last_query()); To display the query result follow this: print_r($query);

How to use query in CodeIgniter?

To submit a query, use the following function: $this->db->query('YOUR QUERY HERE'); The query() function returns a database result object when "read" type queries are run, which you can use to show your results. When "write" type queries are run it simply returns TRUE or FALSE depending on success or failure.

What is query string in CodeIgniter?

CodeIgniter Query String Example: This article shows you how to enable query string in codeigniter. PHP Codeigniter framework uses segment based approach for its URLs, thus making them Search Engine friendly. But those who want to use the good old query string method can turn on this option in code igniter and use it.

How do you check query is executed or not in CodeIgniter?

The update function returns a value: $result = $this->db->update('mytable', $data); Check that value for either being TRUE (success) or FALSE (failure). update runs query internally and then returns the return value of query (Ref):


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


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


You can display the ActiveRecord generated SQL:

Before the query runs:

$this->db->_compile_select(); 

And after it has run:

$this->db->last_query(); 

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

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

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];

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();

You can simply use this at the end..

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