Php Zend Framework : Connecting to multiple databa

2019-02-19 23:07发布

问题:

I have written a script that goes through my application ini.

The problem I am having now is that when I get to the next database, its still selecting from the first database and not the new one.

Is it possible to close a connection and then open a new connection while running a script. Remember this is just a script I have no bootstrap set. I just setup a autoload to that I can load my models.

While looping through sections of the ini

try {
        $db = Zend_Db::factory($section->database->type, $section->database->toArray());
        Zend_Db_Table::setDefaultAdapter($db);
        Zend_Registry::set('db', $db);
    } catch(Zend_Db_Adapter_Exception $e) {
        continue;   
    }

回答1:

See Zend_Application_Resource_Multidb:

application.ini

[production]
resources.multidb.db1.adapter = "pdo_mysql"
resources.multidb.db1.host = "localhost"
resources.multidb.db1.username = "webuser"
resources.multidb.db1.password = "XXXX"
resources.multidb.db1.dbname = "db1"

resources.multidb.db2.adapter = "pdo_pgsql"
resources.multidb.db2.host = "example.com"
resources.multidb.db2.username = "dba"
resources.multidb.db2.password = "notthatpublic"
resources.multidb.db2.dbname = "db2"
resources.multidb.db2.default = true

index.php

$resource = $bootstrap->getPluginResource('multidb');
$db1 = $resource->getDb('db1');
$db2 = $resource->getDb('db2');
$defaultDb = $resource->getDb();


回答2:

For anybody who hasn't got a solution, all you have to do is this:

  1. application.ini -> Define your databases here

    resources.multidb.db.adapter = SQLSRV

    resources.multidb.db.host = localhost

    resources.multidb.db.username = root

    resources.multidb.db.password =

    resources.multidb.db.dbname =

    resources.multidb.db.isDefaultTableAdapter = true

    resources.multidb.db2.adapter = SQLSRV

    resources.multidb.db2.host = localhost

    resources.multidb.db2.username = root

    resources.multidb.db2.password =

    resources.multidb.db2.dbname =

    resources.multidb.db2.isDefaultTableAdapter = false

  2. controller or model where connection to 2nd DB needs to be set up

    $db2Ob = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getResource('multidb')->getDb('db2');

  3. Now use this $db2Ob to execute queries:

    $select = $db2Ob->select()->from(array('db2tbl' => 'table in 2nd DB'),array('column name'))->where(condition);

Hope this helps someone.

Regards,

Supriya Rajgopal