Tag: multiple database in zend

How use different database using zend in a single project

Now, it becomes more difficult if you have a different in how mysql connects to the two schemas. For example different users that each have access on one schema or two different servers.

So let’s start by setting up our test system.

In application.ini we remove the settings we used before and we replace it by the following:

resources.multidb.default.adapter = PDO_MYSQL
resources.multidb.default.host = localhost
resources.multidb.default.username = root
resources.multidb.default.password = ****
resources.multidb.default.dbname = testdb1
resources.multidb.default.default = true

resources.multidb.another.adapter = PDO_MYSQL
resources.multidb.another.host = localhost
resources.multidb.another.username = root
resources.multidb.another.password = ****
resources.multidb.another.dbname = testdb2
resources.multidb.another.default = false

In the bootstrap you add the _initDbRegistry block like below, this will add the different databases to the registry:

* Add databases to the registry
* @return void
public function _initDbRegistry()
$multidb = $this->getPluginResource('multidb');
Zend_Registry::set('db_default', $multidb->getDb('default'));
Zend_Registry::set('db_another', $multidb->getDb('another'));
return $multidb->getDb();

Seperated DB Calls

Let’s first see how we set everything up so we can access each database trough Zend_Db_Table.
Create two model class one is Exampledefault.php and Exampleanother.php. Two table are in different database.

class Exampledefault extends Zend_Db_Table_Abstract
protected $_name = 'exampledefault';
protected $_adapter = 'db_default';


class Exampleanother extends Zend_Db_Table_Abstract
protected $_name = 'exampleanother';
protected $_adapter = 'db_another';


How you can access from controller

Let’s create a helloworld controller.

* Initialize the Controller class
* @param void
* @return void
function init()
$this->table1 = new Exampledefault();
$this->table2 = new Exampleanother(Zend_Registry::get('db_another'));


Now you can access two different database in a single project.

Have a nice day!!!