Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

How do count the number of queries executed

Does Phalcon provide any means to count the number of queries that were run during the creation of a page?



10.6k

I would look at the code here

https://github.com/jymboche/phalcon-debug-widget

They are doing what you want



6.3k
Accepted
answer
<?php

use Phalcon\Events\Event,
       Phalcon\Db\Adapter;

class DbEventListener extends \Phalcon\Mvc\User\Component {

    public function beforeQuery(Event $event, Adapter $connection) {
        $this->dbProfiler->startProfile($connection->getSQLStatement(), $connection->getSQLVariables(), $connection->getSQLBindTypes());
    }

    public function afterQuery(Event $event, Adapter $connection) {
        $this->dbProfiler->stopProfile();
    }

}
<?php

# Attach EM to database adapter 
$di['db']->setEventsManager($di['eventsManager']);

# Create a database profiler
$di['dbProfiler'] = new \Phalcon\Db\Profiler;

# Attach a listener to log each DB query
$di['eventsManager']->attach('db', new DbEventListener);

# Get total statements
$nQueries = $di['dbProfiler']->getNumberTotalStatements();

You can also get the queries as raw SQL, bind types etc

Thank guys!