Magento Tutorials Create An External Database Connection in Magento

« Back to Magento Tutorials

External Database Connection in Magento 1

Creating a custom database connection in Magento 1 is very easy and can be done with a few lines of PHP.

$resource = Mage::getSingleton('core/resource');

/*
 * The below code creates a DB connection with the ID customdb.
 * You will use customdb to retrieve the connection later
 *
 * Ensure you change the username, password and dbname fields
 */
$resource->createConnection('customdb', 'pdo_mysql', array(
  'host'     => '127.0.0.1',
  'username' => 'your_username',
  'password' => 'your_password',
  'dbname'   => 'your_db_name',
  'initStatements' => 'SET NAMES utf8',
  'type'     => 'pdo_mysql',
  'model'    => 'mysql4',
  'active'   => '1',
  'charset' => 'utf8'
));

$dbConnection = $resource->getConnection('customdb');

if (!$dbConnection->isConnected()) {
	throw new Exception('Unable to connect to the DB.');
}

$dbSelect = $dbConnection->select()->from('your_db_table', '*');
	
if ($results = $dbConnection->fetchAll($dbSelect)) {
	print_r($results);
}

External Database Connection in Magento 2

It is just as easy to create a custom database connection in Magento 2. The following example uses the object manager for simplicity, but you may want to use constructor injection in your project.

// You can use constructor injection
$om = \Magento\Framework\App\ObjectManager::getInstance();	

$connectionFactory = $om->get('Magento\Framework\App\ResourceConnection\ConnectionFactory');

/*
 * Create DB connection and save in $dbConnection
 */
$dbConnection = $connectionFactory->create([
  'host'     => '127.0.0.1',
  'dbname'   => 'your_db',
  'username' => 'your_username',
  'password' => 'your_password',
  'active' => '1',
]);

// Init statements to set the charset
$dbConnection->query('SET NAMES UTF8');

/*
 * $dbConnection can now be used in the same way as in Magento 1
 */
$dbSelect = $dbConnection->select()->from('your_db_table', '*');
	
if ($results = $dbConnection->fetchAll($dbSelect)) {
	print_r($results);
}

Blog Strong, Fast & Secure

Make Magento 2 instantly faster by installing our industry recognised optimisation modules.