joomla

Connect to an external db Joomla with Joomla framework

If you need access to tables in the same database of Joomla simplementes then we use the method JFactory->getDBO. For example:

<?php
$db = JFactory::getDBO();
?>
$db is now a  JDatabase type object and can perform operations on the database using standard methods.

But if we want to connect to a completely different to that used by Joomla!  Database. The solution is to use the method JDatabase->getInstance.

<?php
$option = array(); //prevent problems

$option['driver'] = 'mysql'; // Database driver name
$option['host'] = 'db.myhost.com'; // 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 a JDatabase type object and can perform operations on the database using standard methods.

Note: If the database does not use the default port we specify the port number after the name of the host. For example , we could have a MySQL database running on port 3307 (the default port is 3306 ) , then the host name would be ‘ db.myhost.com : 3307 ‘ .

A feature of using JDatabase->getInstance

is that if another call is made with the same parameters previously created object instead of creating a new one will be returned.

Note: However, the parameters must match exactly for this to happen . For example , if two calls made ??to the database using JDatabase->getInstance, using the first as a host name ‘ db.myhost.com ‘ and the second ‘ db.myhost.com : 3306 ‘, then both connections will be different , even though port 3306 is the default , and the parameters are logically the same .