Codeigniter: does $this->db->last_query(); execute a query?
Asked Answered
H

3

48

Does query execution happen at the get_where() clause of the following codeigniter active record statement?

$this->db->select('*');
    $q = $this->db->get_where('Contacts', array('id' => $contact_id));

    $sql = $this->db->last_query();

Or does it happens once you call the result_array()?

And is $this->db->last_query(); a reliable way in getting the query string.

Heaves answered 11/4, 2013 at 16:13 Comment(0)
U
92

The query execution happens on all get methods like

$this->db->get('table_name');
$this->db->get_where('table_name',$array);

While last_query contains the last query which was run

$this->db->last_query();

If you want to get query string without execution you will have to do this. Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions

public function _compile_select($select_override = FALSE)
public function _reset_select()

Now you can write query and get it in a variable

$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();

Now reset query so if you want to write another query the object will be cleared.

$this->db->_reset_select();

And the thing is done. Cheers!!! Note : While using this way you must use

$this->db->from('myTable')

instead of

$this->db->get('myTable')

which runs the query.

Take a look at this example

Unique answered 12/4, 2013 at 7:38 Comment(4)
Welcome and No problemo! They are going to add these two methods(and some other for insert , update and delete etc) in the new version of CI so we will not have to hack it.Unique
@raheelshan this just saved my life. do you have any info about why they made this functions protected ? #9232816Tummy
Please don't call any method with _ which means private access (not from outside). That is no solution but a problem with later updates (when they added real access levels to their methods).Psoriasis
i don't think that method start with _ will create any problem.Paronymous
G
4

For me save_queries option was turned off so,

$this->db->save_queries = TRUE; //Turn ON save_queries for temporary use.
$str = $this->db->last_query();
echo $str;

Ref: Can't get result from $this->db->last_query(); codeigniter

Geriatric answered 20/2, 2020 at 10:42 Comment(0)
H
0

For Me It Works Perfectly: Source Disclosure : This Source website Belongs to me , i am also sharing solutions on my website ...

public function index()
{
    $db = \Config\Database::connect();
    $heroesCount = $db->table('products')->countAll();
    echo $db->getLastQuery();
    exit;
}
Headcheese answered 15/11, 2022 at 17:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.