Looking to Build/Redesign a Website or Blog ?

To speak to Rakshit, call +91 968 704 2303

Multiple MYSQL Database Connection with Zend Framework

Hello Friends,

Do you want to make a connection with multiple database in Zend Framework? Today i worked on multiple MYSQL database connection in Zend Framework as my client wants separate database to reduce the load of site. Its very easy to manage multiple database connection with ZF. You just need to add below code in bootstrap.php file and use the db object accordingly.

public function _initDbAdapter()
{ 
   $parameters = array('host'     => 'server1',
		       'username' => 'user1',
		       'password' => 'pass1',
		       'dbname'   => 'database1'
      		      );
   try 
   {
   	$db = Zend_Db::factory('Pdo_Mysql', $parameters);
 	$db->getConnection();
   }
   catch (Zend_Db_Adapter_Exception $e) 
   {
	echo $e->getMessage();
	die('Could not connect to database.');
   } 
   catch (Zend_Exception $e) 
   {
	echo $e->getMessage();
	die('Could not connect to database.');
   }
   
   Zend_Registry::set('db1', $db);


   $parameters = array('host'     => 'server2',
		       'username' => 'user2',
		       'password' => 'pass2',
		       'dbname'   => 'database2'
      		      );
   try 
   {
   	$db = Zend_Db::factory('Pdo_Mysql', $parameters);
 	$db->getConnection();
   }
   catch (Zend_Db_Adapter_Exception $e) 
   {
	echo $e->getMessage();
	die('Could not connect to database.');
   } 
   catch (Zend_Exception $e) 
   {
	echo $e->getMessage();
	die('Could not connect to database.');
   }
   
   Zend_Registry::set('db2', $db);
}


Let me know if you find any problem.

Thank You!

Share:

1 Comment

Leave a Reply

Your email address will not be published.