get DB handler in CodeIgniter for stand-alone Libraries

We were working on a project where some developers were working with CI and were developing libraries there, and some developers were developing stand-alone libraries. But both groups were working on the same project.

At some point we needed all those stand-alone libraries to be  used in CI as well.
For common code it’s not a big deal, the only problem which took a little bit of time to figure out was using the DataBase. We didin’t want to make new DB connections, so how could we use the current connection, inside an stand-alone code.

The answer is pretty easy, CI’s DB class has a non-documented attribute which returns back the DB handler.


or if you have multiple DB cnnections that would be :


and then you can easily pass the DB connection to regular mysql_query function like this :

mysql_query( string $query[,resource $link_identifier] );

and as an example :

mysql_query( 'SELECT * FROM `table1`', $this->dbr->conn_id );

3 thoughts on “get DB handler in CodeIgniter for stand-alone Libraries

  1. Run into a similar issue when utilizing database handlers/connections.

    I haven’t tested it yet but assume $this->dbr->conn_id is actual db resource and not CI object?

    Following CI Log: “Bugfixes for 1.6.1 – Fixed a bug (#3404) where the MySQLi driver was testing if $this->conn_id was a resource instead of an object.” which is a bit confusing.



  2. @Rad
    Yeah $this->dbr->conn_id is the actual DB resource and not a CI object, that’s why you can use it in a mysql_query function directly.

  3. Pingback: PHP Web Development | Annotary

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s