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.
In CodeIgniter there is a helper function $this->db->last_query(); . This will return the string of the last query.
CodeIgniter Select Query with $this->db->select() This is how you can select records from 'employee_master' table using $this->db->select() method. By default it selects all (*) from given table. The select() method accepts an optional second parameter.
Get last executed query in codeigniter 4 You can easily get the last executed query in Codeigniter 4 using the getLastQuery() method on the \Config\Database::connect(). This method returns the raw SQL query string, not the result.
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);
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With