En Drupal 7 hay varias formas de acceder a bases de datos externas.
Método 1: Añadir bases de datos adicionales en la configuración (settings.php)
<?php $databases = array(); $databases['default']['default'] = array( // Drupal's default credentials here. // This is where the Drupal core will store it's data. ); $databases['my_other_db']['default'] = array( // Your secondary database's credentials here. // You will be able to explicitly connect to this database from your modules. ); ?> |
Y asi es como realizaríamos el cambio de base de datos activa en el módulo…
<?php // Use the database we set up earlier db_set_active('my_other_db'); // Run some queries, process some data // ... // Go back to the default database, // otherwise Drupal will not be able to access it's own data later on. db_set_active(); ?> |
Método 2: definir las bases de datos adicionales “al vuelo” en el propio módulo
Esta forma es la más adecuada si las queries a la base de datos secundaria provienen únicamente de un módulo.
<?php $other_database = array( 'database' => 'databasename', 'username' => 'username', // assuming this is necessary 'password' => 'password', // assuming this is necessary 'host' => 'localhost', // assumes localhost 'driver' => 'mysql', // replace with your database driver ); // replace 'YourDatabaseKey' with something that's unique to your module Database::addConnectionInfo('YourDatabaseKey', 'default', $other_database); db_set_active('YourDatabaseKey'); // execute queries here db_set_active(); // without the paramater means set back to the default for the site drupal_set_message(t('The queries have been made.')); ?> |
The post Drupal 7: acceso a bases de datos externas appeared first on Lecciones Prácticas.