Custom Database Connection in Magento 2 – Instant Method

Welcome Back, to our new post !!

In this article we will learn how to use custom database in existing magento 2 store. So we need to follow below steps:

As in below screenshot, we have a database named ‘custom_magento_table
and a database table name “customer” in which we have three field id, customer_name and customer_group. So let’s try to get data from this custom database table.

Step #1: Edit your app/etc/env.php file and add new custom database connection details ( as follows )

<?php 
return [
--------------------
--------------------
'db' => [
    'table_prefix' => '', // Add prefix if any
    'connection' => [
        'default' => [
            'host' => '<magento_host>',
            'dbname' => '<magento_dbname>',
            ------------------
            ------------------
        ], 
        'custom_db' => [
            'host' => '<custom_host>',
            'dbname' => 'custom_magento_table', // As we created this.. you can add your custom database name here
            'username' => '<db_user>',
            'password' => '<db_password>',
            'active' => '1',
        ],
    ],
],
'resource' => [
    'default_setup' => [
      'connection' => 'default'
    ],
    'custom_db' => [
      'connection' => 'custom_db'
    ]
],

----------------------------------
-----------------------------------
];

Step #2: Now call ResourceConnection in the Helper file as follows:

class CustomTableIntergration{
  private \Magento\Framework\DB\Adapter\AdapterInterface $connection;

  public function __construct(\Magento\Framework\App\ResourceConnection $resource){
    $this->connection = $resource->getConnection("custom_magento_table");
  }

  public function getCustomDatabaseTableData(){
   $select = $this->connection->select()->from(['customer']);
   $datas = $this->connection-> fetchAll($select);
   foreach($datas as $data){
     print_r($data['customer_name']);
   }
  }
}

Output:

cust_1
cust_2

That’s it. Use this data where you need.

See you in next blog !! Happy Coding 🙂

Related Post