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 erro
There are two methods to view the query in CakePHP.
Both methods you have to add the below one line in app/Config/core.php
Configure::write('debug', 2);
First methods :
debug($this->getLastQuery());
where you want to get the query add above line and call this function getLastQuery()
on same controller using below code
public function getLastQuery() {
$dbo = $this->TModel->getDatasource(); //Here TModel is a model.what table you want to print
$logs = $dbo->getLog();
$lastLog = end($logs['log']);
return $lastLog['query'];
}
second method :
add the below line in the any Elements files.
<?php echo $this->element('sql_dump'); ?>
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);
}
This will help you.
echo '<pre>';
$log = $this->YOUR_MODEL->getDataSource();
print_r($log);
exit;
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'];
}
Having a quick skim of the book, cakephp api getLog you could turn on logTransaction
. Although having not used it, I'm not sure how it will perform.
Otherwise you could experiment with FirePHP and here is the a guide for it,
You might try DebugKit, although off the top of my head I think you do still need debug 2 to get it to work.
Hopefully something might give you a lead. :)