Zend_Db Connects to Wrong Mysql Socket

While working on a small project today. I was confronted with a Zend_Db exception that i have seen before. But it still had me searching for a solution. So this time i will write it done for future reference.

I’m working on a small ZF project which uses the MVC structure. And in the Initializer the database connection is setup like this:

public function initDb()
{
  $pdoParams = array(
    PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true
  );
    
  $params = array(
    'host'     => 'localhost',
    'username' => '***********',
    'password' => '***********',
    'dbname'   => '***********',
    'driver_options' => $pdoParams,
  );
    
  $db = Zend_Db::factory('Pdo_Mysql', $params);
  Zend_Db_Table_Abstract::setDefaultAdapter($db);
  Zend_Registry::set('DB', $db);
}

So when i first instantiated a connection to the database i was presented a nice error on screen. The stack trace is quiet long. But this is the most relevant part.

exception ‘Zend_Db_Adapter_Exception’ with message ‘SQLSTATE[HY000] [2002] Can’t connect to local MySQL server through socket ‘/tmp/mysql.sock’ (2)’

The php bug tracker revealed a nice solution. For some strange reason the PDO extension can’t determine the correct socket while the mysql, mysqli extensions can. This is easily solved in the bootstrap of the project by adding an extra parameter to the config array passed when calling Zend_Db::factory();

$params = array(
  'host'     => 'localhost',
  'username' => '***********',
  'password' => '***********',
  'dbname'   => '***********',
  'driver_options' => $pdoParams,
  'unix_socket' => '/var/run/mysqld/mysqld.sock'
);

$db = Zend_Db::factory('Pdo_Mysql', $params);
Zend_Db_Table_Abstract::setDefaultAdapter($db);
Zend_Registry::set('DB', $db);
comments powered by Disqus