How to print last executed query in CakePHP2?

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.

Note: 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);
Shivika Tomar

Shivika Tomar

Shivika Tomar is a passionate PHP developer. Her area of interest is website development. She loves to bring healing to stressful and sad peoples.

Leave a Reply

Your email address will not be published. Required fields are marked *