Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 389
James Bond Avatar asked Apr 11 '13 16:04

James Bond


People also ask

How to check last query in CodeIgniter?

In CodeIgniter there is a helper function $this->db->last_query(); . This will return the string of the last query.

How to get query in CodeIgniter?

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.

How to check last query in CodeIgniter 4?

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.

How can print 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);


2 Answers

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

like image 168
Muhammad Raheel Avatar answered Oct 17 '22 15:10

Muhammad Raheel


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

like image 44
Silambarasan R.D Avatar answered Oct 17 '22 14:10

Silambarasan R.D