Search code examples
zend-frameworkzend-db

zend database connection


In one of our project the database connection specified in application.ini is

resources.db.adapter = Mysqli
resources.db.params.host = localhost
resources.db.params.username = root
resources.db.params.password = ''
resources.db.params.dbname = zf_tutorial

But I required to call the host, username, password and dbname from another file. how to do this?


Solution

  • The accepted answer here is not a good way to get the db object, it should be set up in application.ini as you were doing originally.

    If you want to get another instance of the db object you have several options; you can do as @RockyFord suggests, or you can get the db object from any controller like this:-

    $db = $this->getInvokeArg('bootstrap')->getResource('db');
    

    If you want to go further and have access to the connection details (I can't imagine why you would need them again) then you can get them from the db object like this:-

    $dbConfig = $db->getConfig();
    

    or indeed:-

    $dbConfig = $this->getInvokeArg('bootstrap')->getResource('db')->getConfig();
    

    Which will give you an array containing the connection data, you can try this and do a var_dump($dbConfig); to see the details.

    This is a much more robust way of accessing the db object if you need to, although I would take a long hard look at your overall code design if you need to do this in more than one place, especially if you are accessing the connection details as described here.