How to Connect to an External Database in Joomla with PHP

Below is a PHP snippet allowing you to connect to an external database using the Joomla API.

use Joomla\Database\DatabaseDriver;

// Define the external database driver options
$options = [
	'driver'   => 'mysql',          // The Database driver name
	'host'     => 'db.myhost.com',  // Database host name
	'user'     => 'username',       // User for database authentication
	'password' => 'password',       // Password for database authentication
	'database' => 'database_name',  // Database name
	'prefix'   => 'abc_'            // Database prefix (may be empty)
];

$db = DatabaseDriver::getInstance($options);

// Use the new database driver in your queries
$query = $db->getQuery(true);

$query
	->select($db->quoteName(array('column1', 'column2')))
	->from($db->quoteName('#__table'));

$db->setQuery($query);

$results = $db->loadObjectList();
Last updated on Nov 28th 2024 10:11