2011
06.12

While debugging SQL queries with:

< ?php echo $this->element('sql_dump'); ?>

(in your layout) or DebugKit works great, you have to `render` for it to work. In this particular case that was a problem because I had an `exit;` statement in the middle of my controller to prevent redirection.

The following statement was my rescue:

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

I leaves you a nice SQL log in array format!

PS: make sure to replace Model with an actual model name…

18 comments so far

Add Your Comment
  1. Hi..
    I need your help friend. I want to execute custom sql query in my cakephp app. What should I do with my view file (.ctp)? Example, in my controller :

    function getCount() {

    $qr = “some_queries”;
    $this->set(‘report’, $this->my_model->query($qr));

    }

    Please give me solution for this problem.
    Thank you.

  2. I don’t now for sure if I understand what you mean, but if you set `report` in your controller (by using custom sql or find) you can use it as `$report` in your view.

  3. I span the wheel a little bit further and made a switch to output/die or log/continue:
    http://www.dereuromark.de/2011/06/06/very-useful-cakephp-code-snippets – “SQL queries anywhere in the app”

  4. Very nice!

  5. wont work in production mode.

  6. to work in produce mode you need to change the Configure::write(‘debug’, 0); to Configure::write(‘debug’, 2); in config/core.php

  7. Thats true but you probably don’t want to log SQL queries in production mode. Also Configure::write(‘debug’, 2) is bad for performance since caches are invalidated immediately.

  8. Thanks for making it so clear and exceptional guidance.I’ll probably be again to read much more, thanks for that info.

  9. How can I access the Model class within my own libary?

  10. Can you show me a piece of code to explain yourself?

  11. hi can u please help me with this asap!!!!

    I’ve a code in which the values are not getting posted to database. The code below is a part of controller in which the query is not saving data to database please go through it and give me the solution.

  12. Please supply a pastebin link instead of this massive piece of code…

  13. I am getting

    Error: Call to a member function getDataSource() on null

  14. That means that you’re calling it on a non-existing model (e.g. change Model to User)

  15. any way this would work even if the debug mode is set to 0?

  16. No, not that I’m aware of. You can implement a custom (MySQL) DataSource

  17. […] How to debug SQL queries from a controller in cakePHP […]