This post is about Zend Framework, sql error reporting.

Problem:
If your SQL has an error in it, Zend Framework throws a Zend_Db_Statement_Mysqli_Exception, the default exception message is pretty pants and does not show the whole SQL query (it only shows the first 10 characters or so!)

Lets fix it so it shows the whole query.

I found this neat class that reports the SQL, it work by extending the Zend_Db_Adapter_Pdo_Mysql class. I use MySQLi, so I adapted it so it works for me:

class MyCompany_Db_Mysqli extends Zend_Db_Adapter_Mysqli
{

public function query($sql, $bind = array()) {
try {
return parent::query($sql, $bind);
} catch (Exception $e) {

if( $this->getProfiler()->getEnabled() )
{

                echo ‘<span style=”color: red; font-size: 20px;”>MyCompany_Db_Mysqli adapter Error</span>’;
echo ‘<div style=”font-family: monospace; padding: 10px; margin: 10px; border: 2px solid pink;”>’;
echo nl2br($sql);
echo ‘<hr>’;
echo ‘<pre>’;
echo var_dump($bind);
echo ‘<pre>’;
echo ‘</div>’;
}
else
{
// no profiler
throw $e;
}
}
}
}

The whole thing is a little bit quick and dirty. I wanted to see if it worked and post a blog entry about if it did.

You need to save the file into your library code (replace MyCompany with your library directory name) in the Db directory.

To use it you want to find where you load your database adapter, I do this in my controller init() function. My init() looks like this:

class ProjectsController extends Zend_Controller_Action
{
//
// this is called from __construct
//
public function init()
{
parent::init();

$config = new Zend_Config_Ini(‘/var/www/ZF-apps/config.ini’, ‘general’);

//$db = Zend_Db::factory($config->projects->db);
$db = new Guava_1_Db_Mysqli($config->projects->db->params);
$db->getProfiler()->setEnabled(true);
Zend_Db_Table::setDefaultAdapter($db);

Note how I have commented out how I used to get my adapter. Also see how the params are loaded from an .ini file and used slightly differently.

How to use it:
On my staging (development) server I use the SQL profiler (the highlighted blue line), so if the profiler is enabled then I’d like to see the SQL errors. If I am not profiling (on the live server) then I just raise the error like normal.

You’ll want to add your own logic into the adapter so it emails off the error report (or pasts it into an RSS feed or something)