How to connect Joomla with an external database?

Monday, July 21, 2014

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.


<?php
   $db = JFactory::getDbo();
?>

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.

<?php

$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'] = '';   // Password for database authentication
$option['database'] = 'another_db';      // Database name
$option['prefix']   = 'pre_';             // 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.

You Might Also Like

0 comments