We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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?



16.4k

I would look at the code here

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

They are doing what you want



6.4k
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!