Follow the following steps to print last executed query in CakePHP2:
To print last executed query:
Add below code in app_model.php file which is located at root/cake/libs/model.
public function getLastQuery() {
Configure::write('debug', '2');
$dbo = $this->getDatasource();
$logs = $dbo->getLog();
$lastLog = end($logs['log']);
return $lastLog['query'];
}Add below line in your model where you want print query.
$last_query = $this->ModelName->getLastQuery();
As we have saved last executed query in variable $last_query then use this to print last executed query.
Remarque : the above code will work only if your model extends appModel because we have defined function in app_model.php
To print all executed queries:
Write below code in model to display all queries which were executed in code:
$log = $this->Model->getDataSource()->getLog(false, false); debug($log);