Tag Archive: databases

Conditional Auto-Loading of Libraries in CodeIgniter

I’ve recently begun digging into CodeIgniter for a new project I’m working on. One of the first things that strikes me is the lack of a good way to set up your database tables. The standard method seems to be, in a nutshell: point and click in PHPMyAdmin or import a SQL file from the command line.

So, step 1: create an Install controller. This is a pretty basic controller that you access at http://example.com/install (and which you’ll disable after developing the site). All it does is create the database tables you’ll need and add any initial values you might want. You can figure the rest of it out on your own.

But I have a problem. I want to auto-load the session library for all of my controllers. That’s easy enough: just add $autoload['libraries'][] = 'session'; to your autoload.php file. The session library, though, requires a properly-defined table to exist in the database before it can be used.* If you auto-load it, though, it will also auto-load for the Install controller, which won’t work, since the tables haven’t been installed, yet.

*Technically, it can work without a database, but then I’d have to keep changing a configuration setting every time I want to re-install the database, which I’m doing rather frequently in the early stages of building this app.

So, I made a hack to get around that. Please note that I do not recommend this on a production site. This is for development purposes only.
Continue reading

Connect to Multiple Databases from Drupal

Drupal has the ability to connect to multiple databases, allowing you to use Drupal’s built in database abstraction layer on more than just Drupal’s primary database.

The “proper” way to do it (according to Pro Drupal Development and the Module Developer’s Guide) is to change $db_url in your settings.php file from a string to an array, e.g.:

$db_url['default'] = 'mysqli://user:[email protected]/drupal';
$db_url['alternate'] = 'mysqli://user:[email protected]/alternate_db';

Then you can switch from one database to another quite easily:

db_set_active('alternate');
// do stuff...
db_set_active('default');

What if you want your alternate database to be configurable through a settings page, though? You can’t set that in the settings.php file. The solution is pretty simple, actually: just edit $db_url to add in your new database.

global $db_url;
if ( !is_array($db_url) ) {
  $db_url = array( 'default' => $db_url );
}
$protocol = 'mysqli'; // or use variable_get() to get the variable you set on your settings page
$user = 'user';
$pass = 'password';
$host = 'localhost';
$db = 'alternate_db';
$db_url['alternate'] = "$protocol://$user:$pass@$host/$db";
$previous = db_set_active('alternate'); // returns the previous db name
// do stuff...
db_set_active($previous); // return to whatever database was active before

Drupal will check $db_url every time db_set_active is called, so you can edit it whenever you need.