1

I have multiple sites setup on a single MySQL database in Drupal 6. The sites each have their own prefix, such as site1_, site2_, etc. I'm wondering how I can switch the current table prefix inside of a module to check the variables on each site. For example, I want to check the preprocess_css variable on every site by looping through each sites settings file and running variable_get('preprocess_css') and get the variable for each site. I can get the table prefix and get the variable using db_query on the variables table, but I know there has to be a way to set the current table prefix inside a module so I can just run variable_get inside a loop with each table prefix. Does anyone know how this can be done?

0

The problem with variable_get() is that it doesn't read values from the database, but from a global variable, which is initialized during the Drupal bootstrap.

function variable_get($name, $default) {
  global $conf;

  return isset($conf[$name]) ? $conf[$name] : $default;
}

What you should do is use code similar to the following one.

$variables = array();
$old_db_prefix = $GLOBALS['db_prefix'];
$GLOBALS['db_prefix'] = 'site1_';
$result = db_query('SELECT * FROM {variable}');

while ($variable = db_fetch_object($result)) {
  $variables[$variable->name] = unserialize($variable->value);
}

$GLOBALS['db_prefix'] = $old_db_prefix;

Then you can read the value of, e.g., preprocess_css, with $variables['preprocess_css'].

You could use code similar to the following one.

function mymodule_variable_get($db_prefix, $name, $default) {
  $old_db_prefix = $GLOBALS['db_prefix'];
  $GLOBALS['db_prefix'] = $db_prefix;
  $value = db_result(db_query("SELECT value FROM {variable} WHERE name = '%s'", array($name)));
  $GLOBALS['db_prefix'] = $old_db_prefix;

  return !empty($value) ? unserialize($value) : $default;
}

Bear in mind that some Drupal variables can be overridden with a value set in the settings.php file, which can contains code similar to the following one.

$conf = array(
  'preprocess_css' => FALSE,
);

What you read from the database could not be the value set for that Drupal site, for the Drupal variable you are reading.

0

The prefix is stored as one of the variables in the settings.php file, all of which are made global early on in the page build process.

That in mind, you can do something as easy as:

$GLOBALS['db_prefix'] = 'db1_';
print variable_get('site_name', 'default'); // Site name from first set of tables

$GLOBALS['db_prefix'] = 'db2_';
print variable_get('site_name', 'default'); // Site name from second set of tables

Bear in mind that this change won't persist across page loads so you'll need to do your processing in a single load, or implement some sort of system to track which prefix you should currently be using.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.