Request Quote

Add More Than One Connection With Multiple Database in Magento2

Add More Than One Connection With Multiple Database in Magento2.

Today I am going to explain that how you can add multiple connections with multiple databases in magento 2 in this article. Suppose you have to display some data from another database instead of magento’s default database so this blog will be very helpful for you.

At first you will need to edit app/etc/env.php, to give connection configuration for another database, like below:

 

 'db' =>
  array (
    'table_prefix' => '',
    'connection' =>
    array (
      'default' =>
      array (
        'host' => 'localhost',
        'dbname' => 'magento2',
        'username' => 'magento2_username',
        'password' => 'magento2_password',
        'active' => '1',
      ), // this array is from magento default
      'custom' =>
      array (
        'host' => 'localhost', //your custom db host
        'dbname' => 'customdb', //your custom db name
        'username' => 'cuatom_username', //your custom db username
        'password' => 'custom_password', //your custom db password
        'active' => '1', // 1 is for active database 
      ), // this array is added by me
    ),
  ),
  'resource' =>
  array (
    'default_setup' =>
    array (
      'connection' => 'default', 
    ), //this is magento default array
    'custom' =>
    array (
      'connection' => 'custom',
    ), //this resource is given by me
  ),

 

Now, you have a controller file in which you want data from custom database, then below is the code for that:

 

<?php
namespace Company\Module\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;

class Index extends Action
{
     private $connection;

    /**
     * @param Context                               $context
     */
    public function __construct(
        Context $context,
        \Magento\Framework\App\ResourceConnection $resourceConnection
    ) {
        $this->connection = $resourceConnection->getConnection('custom'); // "custom" is your database connection name which is given in env.php
        parent::__construct($context);
    }

    public function execute()
    {
        try {
            $select = $this->connection->select()->from(['student_info']); //student_info is a table in customdb, this query is to select table
            $data = $this->connection->fetchAll($select); //here fetching all rows from student_info table
            echo "<pre>";
            print_r($data); //print that data in array
        } catch (\Exception $e) {
        }
    }
}

 

Now when you hit above controller output will be as follows :

data in table

data when you print

 

Hope this blog will help you to develop custom functionality in your module in a better way. Try this and if you have any query then just comment below 🙂

. . .

Comment

Add Your Comment

Be the first to comment.

css.php