Search code examples
zend-frameworkzend-dbzend-db-select

Use of select queries in Zend Framework without providing database info


I use select queries as by following code:

$params = array(
        'username' => 'root',
        'password' => '',
        'dbname' => 'mst2');
    $db = Zend_Db::factory('pdo_mysql', $params);

$select = $db->select()
            ->from(array('dc' => 'delivery_center'))
            ->join(array('r' => 'region'), 'dc.region_id = r.region_id');
    $stmt = $select->query();
    $result = $stmt->fetchAll();

Here $db is the credentials of the database that I am using.But I have specified the credentials in application.ini already by following lines:

resources.db.params.host = localhost
resources.db.params.username = root
resources.db.params.password = ''
resources.db.params.dbname = mst2

Now logically I should not provide these credentials again.But I have to use select queries.So how $db should be initialized without proving database credentials again??Thanks in advance.


Solution

  • Db resource is available by default and is initialized automatically whilst bootstraping.

    If you want to get database adapter in your application you can get it as plugin resource from bootstrap:

    $resource = $bootstrap->getPluginResource('db');
    $db = $resource->getDbAdapter();
    

    If you do not have reference to bootstrap you always can retrieve it from FrontController:

    $front = Zend_Controller_Front::getInstance(); 
    $bootstrap = $front->getParam('bootstrap');