CakePHP - get last query run

Phantz picture Phantz · Mar 26, 2010 · Viewed 80.2k times · Source

I want to get the last query CakePHP ran. I can't turn debug on in core.php and I can't run the code locally. I need a way to get the last sql query and log it to the error log without effecting the live site. This query is failing but is being run.

something like this would be great:

$this->log($this->ModelName->lastQuery);

Thanks in advance.

Answer

Matt picture Matt · Apr 18, 2012

For Cake 2.0, the query log is protected so this will work

function getLastQuery() {
  $dbo = $this->getDatasource();
  $logs = $dbo->getLog();
  $lastLog = end($logs['log']);
  return $lastLog['query'];
}