• Page:
  • 1

Connecting to another database using JDatabase in joomla

OFFLINE

Connecting to another database using JDatabase in joomla

7 years, 3 months ago
Doing a database connection is pretty simple in joomla, it is just a one line code

$db = JFactory::getDBO();


This connects you to the joomla database, now if you want to connect to some other database then too you can use JDatabase class of joomla. Here are the lines of code that will connect you to your new database

		
                jimport('joomla.database.database');
		jimport( 'joomla.database.table' );

		$conf =& JFactory::getConfig();

		$host 		= '192.168.1.2'; //replace your IP or hostname
		$user 		= 'db_user'; //database user
		$password 	= 'db_pass';//database password
		$database	= 'db_name'; //database name
		$prefix 	= 'jos_'; //prefix if any else just give any random value
		$driver 	= 'mysql'; //here u can also have ms sql database driver, postgres, etc
		$debug 		= $conf->getValue('config.debug');

		$options	= array ( 'driver' => $driver, 'host' => $host, 'user' => $user, 'password' => $password, 'database' => $database, 'prefix' => $prefix );

		$db =& JDatabase::getInstance( $options );

		if ( JError::isError($db) ) {
			header('HTTP/1.1 500 Internal Server Error');
			jexit('Database Error: ' . $db->toString() );
		}

		if ($db->getErrorNum() > 0) {
			JError::raiseError(500 , 'JDatabase::getInstance: Could not connect to database <br />' . 'joomla.library:'.$db->getErrorNum().' - '.$db->getErrorMsg() );
		}

		$db->debug( $debug );
		


thanks
Last Edit: 7 years, 3 months ago by Priyanka Jain.
The following user(s) said Thank You: Deepesh Chang, Ninad Ramade, Hirdesh Vishwdewa, Rajat Pal
OFFLINE

Re: Connecting to another database using JDatabase in joomla

6 years, 9 months ago
Even closing of the connection is necessary i think:
Just add this after you're done with query operations.
 $db->__destruct(); 
The following user(s) said Thank You: Hirdesh Vishwdewa
OFFLINE

Re: Connecting to another database using JDatabase in joomla

6 years, 9 months ago
Yes, I guess that would be a good practice to do.

But, even if you do not, then it is fine, because JDatabase always creates a non-persistent connection which automatically timesout after a certain time of inactivity.

The following user(s) said Thank You: Hirdesh Vishwdewa
  • Page:
  • 1

Upcoming Events

Who's Online

0 users online