Connect to an external (non-drupal) database

Public

Sometimes we want to communicate with another website/application database e.g. to manage mailing list or ads. There is a simple and quick way to achieve this by use some static methods of Database class .
It's works well for me, but feel free to write suggestion about any improvements to this solution.

Get raw version
php
  1. //Example module
  2.  
  3. $db = array(
  4. 'host' => 'example_database_host',
  5. 'database' => 'example_database_name',
  6. 'username' => 'example_database_user',
  7. 'password' => 'example_database_password',
  8. 'driver' => 'mysql',
  9. );
  10. //
  11. Database::addConnectionInfo('example_module', 'example_target', $db);
  12.  
  13. //Get 'id' and 'name' fields from 'table_name' table in the external database.
  14. $query = Database::getConnection('example_target', 'example_module')->query("SELECT id, name FROM table_name");
  15.  
  16. //Do something with received data.

You can also configure new database connection in settings.php file. Just remove following code from your module

Get raw version
php
  1. $db = array(
  2. 'host' => 'example_database_host',
  3. 'database' => 'example_database_name',
  4. 'username' => 'example_database_user',
  5. 'password' => 'example_database_password',
  6. 'driver' => 'mysql',
  7. );
  8. //
  9. Database::addConnectionInfo('example_module', 'example_target', $db);

and add some configuration to settings.php file:

Get raw version
php
  1. $databases['example_module']['example_target'] = array(
  2. 'host' => 'example_database_host',
  3. 'database' => 'example_database_name',
  4. 'username' => 'example_database_user',
  5. 'password' => 'example_database_password',
  6. 'driver' => 'mysql',
  7. );