Difference between revisions of "Connecting to an external database"

From Joomla! Documentation

m (Added category)
m (moved How to connect to an external database to Connecting to an external database: Adapted page title to the continuous tense used in most tutorial titles)
(No difference)

Revision as of 14:32, 7 February 2012

If you need to access tables within the same database as your Joomla! installation then you can simply use the JFactory->getDBO method. This uses the already established connection that Joomla! uses to connect to the database. For example:

$db = JFactory::getDBO();

$db is now an object of type JDatabase and you can perform database operations on it using the usual methods.

But what if you want to connect to a completely different database from the one used by Joomla!?. This might be a different database on the same machine as your Joomla! site or it might be on a different host and perhaps even require a different database driver. Well, you can do this using the JDatabase->getInstance method.

$option = array(); //prevent problems
$option['driver']   = 'mysql';            // Database driver name
$option['host']     = '';    // Database host name
$option['user']     = 'fredbloggs';       // User for database authentication
$option['password'] = 's9(39s£h[%dkFd';   // Password for database authentication
$option['database'] = 'bigdatabase';      // Database name
$option['prefix']   = 'abc_';             // Database prefix (may be empty)
$db = & JDatabase::getInstance( $option );

$db is now an object of type JDatabase and you can perform database operations on it using the usual methods.

Note that if the database uses a non-standard port number then this can be specified by adding it to the end of the host name. For example, you might have your MySQL database running on port 3307 (the default is port 3306), in which case your host name might be ''.

One feature of using JDatabase->getInstance is that if another call is made with the same parameters it will return the previously created object rather than creating a fresh one.

Note, however, that the parameters must match exactly for this to happen. For example, if two calls were made to a MySQL database using JDatabase->getInstance, with the first using a host name of '' and the second using '', then two separate connections would be made, even though port 3306 is the default port for MySQL and so the parameters are logically the same.