Skip to Content

Accessing other database connections in Symfony

Some cookbook code to access other databases within a Symfony 1.4 project using Doctrine.

I needed to access other databases in my Symfony 1.4 project using the Doctrine data manager to pull out information that was not part of my existing Symfony database schema. I also wanted to be able to set the configuration parameters within the databases.yml file to prevent hard-coding values.

So first I set up the other database in the databases.yml file:

    class: sfMySQLDatabase
      dsn: 'mysql:host=localhost;dbname=other_database'
      username: my_db_username
      password: my_db_password

The important thing to note here is the class. If you set that to 'sfDoctrineDatabase' then that will expect to be able to use your existing database schema. You can set it to 'sfMySQLDatabase' to prevent that from happening.

Then in your actions file, use this:

// get the details of the database you want to connect to from the 
$ajs_db = sfContext::getInstance()->getDatabaseManager()
// create an array of parameters to create the dsn connection
$params = array(
// open this connection, setting false prevents this connection 
replacing your default one
$conn = Doctrine_Manager::getInstance()
    ->openConnection($params, 'name_of_connection', false);
// create your query
$query = "SELECT * FROM jobs";
// execute your query
$this->jobs =  $conn->fetchAll($query); 

Done. Note that there are a varierty of different doctrine methods you can use to retrieve data. For instance, fetchall returns an associative array of each row. There are others like count, fetchRow etc. You can view these at Connection.php within the doctrine plugins folder of your Symfony installation.

Hope that helps!