02/09/08

Zend framework: Logging Database Queries to FireBug

Logging database queries to FireBug is sinfully simple with the new component Zend_Db_Profiler_Firebug in ZF 1.6, now available, you can download it here Zend Framework Download Page.

Requirements:

  1. Firefox Browser ideally version 3 but version 2 is also supported.
  2. Firebug Firefox Extension.
  3. FirePHP Firefox Extension.

More information on requirements at the Zend Framework Documentation -  Profiling with Firebug

Let’s look at some examples.

< ?php
// Instatiate the database
$db = Zend_Db::factory('Pdo_Mysql',
    array(
        'host' => 'localhost',
        'dbname' => 'zf_feature_testing',
        'username' => 'user123',
        'password' => 'pass123'
    )
);
 
// Instantiate the profiler in your bootstrap file 
$profiler = new Zend_Db_Profiler_Firebug('All Database Queries:');
// Enable it
$profiler->setEnabled(true);
// Attach the profiler to your db adapter 
$db->setProfiler($profiler);
 
// Run your queries
$result1 = $db->fetchAll('SELECT * FROM zf_test');
$result2 = $db->fetchAll('SELECT * FROM zf_test where id = ?', 3);

Alternatively you can add the profiler parameters to the Zend_Db factory.

< ?php
// Instatiate the database, passing in the profiler parameters.
$db = Zend_Db::factory('Pdo_Mysql',
    array(
        'host' => 'localhost',
        'dbname' => 'zf_feature_testing',
        'username' => 'user123',
        'password' => 'pass123',
        'profiler' => array(
            'enabled' => true,
            'class' => 'Zend_Db_Profiler_Firebug'
        )
    )
);

Or from an .ini file using Zend_Config_Ini

$config = new Zend_Config_Ini('../application/config.ini', 'development');
$db = Zend_Db::factory($config->database);

config.ini

[development]
database.adapter                    = pdo_mysql
database.params.host                = localhost
database.params.username            = user123
database.params.password            = pass123
database.params.dbname              = zf_feature_testing
database.params.profiler.enabled    = true
database.params.profiler.class      = Zend_Db_Profiler_Firebug

Show me my profiling data?

Open FireBug, you will see a link under console.

Profiling with FireBug

Click it open and it will list all the queries that were run.

Profiling with FireBug

Enjoy!