Codeigniter: does $this->db->last_query(); execute

2019-04-03 01:38发布

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.

1条回答
Emotional °昔
2楼-- · 2019-04-03 02:05

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

查看更多
登录 后发表回答