Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP - get last query run

People also ask

How to print last executed query in php?

print_r($this->db->last_query()); As like what is the code for printing last executed query in PHP?

How to print sql query in CakePHP?

To print out all queries run in a given page request, in your controller (or component, etc) run: $this->render('sql');


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'];
}

Tested in CakePHP v2.3.2

$log = $this->Model->getDataSource()->getLog(false, false);
debug($log);

In CakePHP 1.x, the data you want is accessible in DataSource::_queriesLog. Cake doesn't really provide a getter method for this member, but the underlying language being PHP, nothing stops you from doing the following:

In app/app_model.php:

function getLastQuery()
{
    $dbo = $this->getDatasource();
    $logs = $dbo->_queriesLog;

    return end($logs);
}

You can use this inline.

$dbo = $this->Model->getDatasource();
// store old state
$oldStateFullDebug = $dbo->fullDebug;
// turn fullDebug on
$dbo->fullDebug = true;

// Your code here! eg.
$this->Model->find('all');

// write to logfile
// use print_r with second argument to return a dump of the array
Debugger::log(print_r($dbo->_queriesLog, true));
// restore fullDebug
$dbo->fullDebug = $oldStateFullDebug;