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

I leaves you a nice SQL log in array format!

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

15 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. […] was explained in this post: https://blog.tersmitten.nl/archives/1172 and it does works wonders. All you need to do is to change the "Model" for your model […]

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

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

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

  12. 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.

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

  14. I am getting

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

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