Accessing an alternate database from a CodeIgniter hook

I was writing a url-based access control hook for this CI web app recently, and I was scratching my head how to access a database from the hook.

The standard $this->load->database() call doesn’t work because we are not within a controller, and then I stumbled upon the get_instance() method:

$CI =& get_instance();
$CI->load->database();
$query = $CI->db->get("groups");

Now I began my development on the frontend to setup the permissions itself, so I had always thought that the 2nd statement was working well.

When I began applying the hook to the actual app, I found that $ci->db actually referred to the default database that is specified in system/application/config/database.php even if I put in a argument.

Seems like there’s nothing posted about this, so here’s the solution, in case anybody needs it:

$CI =& get_instance();
$db = $CI->load->database("access", true);
$query = $db->get("groups");

Note the semantic differences between the two. I would have much appreciated it if my call to $ci->load->database() triggered some kind of CI error, since it does not, in fact, work correctly.

Tested successfully in v1.5.3. Your mileage will vary.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s