While debugging SQL queries with:


(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);

I leaves you a nice SQL log in array format!

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

17 comments so far

Add Your Comment
  1. Mischa ter Smitten

    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. Mischa ter Smitten

    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. Mischa ter Smitten

    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. Mischa ter Smitten

    Very nice!

  5. Mischa ter Smitten

    wont work in production mode.

  6. Mischa ter Smitten

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

  7. Mischa ter Smitten

    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. Mischa ter Smitten

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

  9. Mischa ter Smitten

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

  10. Mischa ter Smitten

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

  11. Mischa ter Smitten

    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. Mischa ter Smitten

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

  13. Mischa ter Smitten

    I am getting

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

  14. Mischa ter Smitten

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

  15. Mischa ter Smitten

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

  16. Mischa ter Smitten

    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 […]