views:

731

answers:

3

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.

+1  A: 

Having a quick skim of the book, http://api.cakephp.org/class/model you could turn on 'logTransaction'. Although having not used it, I'm not sure how it will perform.

Otherwise you could experiment with FirePHP http://www.firephp.org/ and here is the a guide for it, http://bakery.cakephp.org/articles/view/debugging-with-firephp

You might try DebugKit, http://github.com/cakephp/debug_kit 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. :)

DavidYell
+3  A: 

The data you want is 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);
}
Daniel Wright
When I try using this function I only get "2010-03-29 11:13:29 Error: " in the error log file. I used $this->log($this->Job->getLastQuery());
Phantz
$this->log(var_export($this->Job->getLastQuery(),true));
Phantz
Where are you calling $this->log()? Also, you might want to debug the output from Model::getLastQuery before throwing it in the log. It might be returning an array, causing an array-to-string conversion error.
Daniel Wright
+1  A: 

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;
blavla