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.

tread
  • 10,133
  • 17
  • 95
  • 170
James Bond
  • 699
  • 1
  • 10
  • 17

3 Answers3

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

Community
  • 1
  • 1
Muhammad Raheel
  • 19,823
  • 7
  • 67
  • 103
  • 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. – Muhammad Raheel Apr 12 '13 at 12:22
  • @raheelshan this just saved my life. do you have any info about why they made this functions protected ? http://stackoverflow.com/questions/9232316/is-there-a-function-like-compile-select-or-get-compiled-select – mirza Jul 11 '13 at 05:20
  • 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). – Roland Sep 20 '17 at 15:53
  • i don't think that method start with _ will create any problem. – Muhammad Zaman Apr 09 '18 at 12:47
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

Silambarasan R
  • 1,346
  • 15
  • 22
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;
}
Ahtesham
  • 1
  • 2