I am writing am module that gets some data from an external database. I have been able to query the external database with the information from

http://drupal.org/node/18429

is there a way to get a module to add an external database reference without modifying settings.php by hand?

Comments

BladeRider’s picture

You should be able to modify the global $db_url variable yourself - something along the lines of the (untested, untried!) code below.

As always, with modifying globals, you might break modules that maintain internal caches based on them.


/**
 * $name is what you want to name the reference
 * $ref is a string the the same format as the $db_url in settings.php
 */
function add_db_ref($name, $ref) {

  $global $db_url;

  // If current $db_url is not an array make it one (and don't forget to insert the default connection)
  if (!is_array($db_url)) {
    $default = $db_url;
    $db_url = array();
    $db_url['default'] = $default;
  }

  // Add the new reference
   $db_url[$name] = $ref;
}

agerson’s picture

Thanks BladeRider,

I tested this and it does work. The only correction is:

$global $db_url;

should be

global $db_url;

Is there any community consensus on this technique vs just using the built in php mysql_connect, mysql_query, etc... functions inside a custom module wanting external sql data? One drawback to using the php mysql functions is security concerns.

Is there a more secure way to use the built in functions:

<?php
mysql_connect($server, $username, $password) or drupal_set_message(mysql_error(),'warning');
  mysql_select_db("moodle") or drupal_set_message(mysql_error(),'warning');
  $query = "SELECT bla bla bla ...
  WHERE usr.username = '".check_plain($user->name)."'";

  $result = mysql_query($query) or drupal_set_message(mysql_error(),'warning');

  while($row = mysql_fetch_array($result)){
    $coursename = check_plain($row['fullname']);
  }

?>
mariamma’s picture

Hi,
I too needed the same help. i want to query an external database using drupal. Since I am very new to Drupal , just don't know how to get started. I tried reading on the book Pro-Drupal Dev, but doesn't seem to help me much. Can you tel me how should I go forward or give me tips in hardcoding?