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 I view a SQL Statement?

I want to view the SQL statement that is about to be executed below :


 //Deleting existing robot
 $success = $connection->delete(
     "id = 101"
 //Next SQL sentence is generated
 DELETE FROM robots WHERE id = 101

How can I add some kind of listener or just plain var_dump the select query that is about to generated by the $connection->delete


For me, the easiest solution is to just enable the query log, then tail -f that file as you run queries.


I am use this approach:

$config = new \Phalcon\Config([
    'db' => [
        'adapter'       => 'Mysql',
        'host'          => 'localhost',
        'dbname'        => 'test',
        'username'      => 'root',
        'password'      => ''
    'path' => [
        'controllers'   => __DIR__.'/../app/controllers/',
        'libraries'     => __DIR__.'/../app/libraries/',
        'messages'      => __DIR__.'/../app/messages/',
        'models'        => __DIR__.'/../app/models/',
        'views'         => __DIR__.'/../app/views/',
        'tmp'           => __DIR__.'/../tmp/',
$di->set('db', function() use ($config) {
    $adapter = '\Phalcon\Db\Adapter\Pdo\\'.$config->db->adapter;
    $connection = new $adapter((array) $config->db);
    $logger = new \Phalcon\Logger\Adapter\File($config->path->tmp.'sql.log');
    $eventsManager = new \Phalcon\Events\Manager();
    $eventsManager->attach('db', function($event, $connection) use ($logger) {
        if ($event->getType() == 'beforeQuery') $logger->log($connection->getSQLStatement().' '.join(', ', $connection->getSQLVariables()));
    return $connection;


Hey thanks all, I followed your advice @urulab. I also added a nice Exception to catch those Phalcon\Db exceptions.

catch (\Exception $e) {
            echo get_class($e), ": ", $e->getMessage(), "\n";
            echo " File=", $e->getFile(), "\n";
            echo " Line=", $e->getLine(), "\n";
            //return array('error' => 'General Exception', 'trace' => $e->getTraceAsString());