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

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

<?php

 //Deleting existing robot
 $success = $connection->delete(
     "robots",
     "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

Thanks

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



174
Accepted
answer

I am use this approach:

<?php
$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()));
    });
    $connection->setEventsManager($eventsManager);
    return $connection;
});


22.8k

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