Thursday, April 18, 2013

Joomla - Connecting to an external database

Two methods to access the database in joomla .

1)JFactory->getDBO()  
2)JDatabase->getInstance()


If you need to access tables within the same database as your Joomla! . Simply use the JFactory->getDBO method. This uses the already established connection that Joomla! uses to connect to the database.

Example (Internal database access):


$db = JFactory::getDBO();


But  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.

Example (External database access):

$option = array(); //prevent problems
 
$option['driver']   = 'mysql';        // Database driver name
$option['host']     = 'localhost';    // Database host name
$option['user']     = 'root';         // User for database authentication
$option['password'] = 'root';         // Password for database authentication$option['database'] = 'databasename'; // Database name
$option['prefix']   = 'abc_';         // Database prefix (may be empty)
 
$db = & JDatabase::getInstance( $option );

Cheers friends!!!

No comments:

Post a Comment