问题
I am using cakephp v3.x and mysql.
I would like to see the SQL query of a controller. There is no error with this controller and it runs successfully.
public function appGetResult()
{
$this->autoRender = false;
$start_date = $this->request->query['start_date'];
$end_date = $this->request->query['end_date'];
$results = $this->MonthlyReports->getResult($start_date, $end_date);
echo json_encode($results);
}
How to modify the controller code to display the SQL query used in generating the results? This is not for actual production use. More for examination.
回答1:
You can turn on query logging on CakePHP3: http://book.cakephp.org/3.0/en/orm/database-basics.html#query-logging
If you're interested in doing more debugging and such, DebugKit does an amazing job.
回答2:
I figured out an indirect way for an answer to my own question. This is an indirect way to see the MySQL query statements.
public function appGetResult()
{
//$this->autoRender = false;
$start_date = $this->request->query['start_date'];
$end_date = $this->request->query['end_date'];
$results = $this->MonthlyReports->getResult($start_date, $end_date);
echo json_encode($results);
}
By commenting away $this->autoRender = false;
and not having a view .ctp, the php page stops with an error. The DebugKit panel will be shown on the erroneous webpage. From the DebugKit panel, one will be able to see the SQL statements.
回答3:
You can use getLog() or showLog() function to do it
var_dump($this->MonthlyReports->getDataSource()->getLog(false, false));
var_dump($this->MonthlyReports->getDataSource()->showLog());
来源:https://stackoverflow.com/questions/33628161/show-sql-query-of-controller