As we all know Magento is a one of the most popular ecommerce technologies, which also provides a reliabile method to use its multiple features which helps to increase sales growth as well as manage everything from Admin panel which makes it little complex as well.
So, as its complexity increases with its functionalities. It also provides a feature to connect more that one Database with the same instance and use its data for our work or to increase further validation for the Magento instance. It totally depends upon us, how we need to use it in multiple ways.
So, Let’s start with this Topic.
By default, we all know Magento uses a single Database to run and save the data of the store. All Database credentials are store in env.php file at magento_root/app/etc/env.php
So, to connect our new Database, we need to first provide access in the parameters which Magento accepts.
New Connection Setup
Here in the above env.php file, we have added our Custom database to create a connection.
Here, connection_name will be some specific name(string) given to identify the custom database. connection_name_setup name will be given in the resource which will be used to fetch the data from this DB.
Here we have created our connection with the new DB. But make sure the DB exists and the given credentials of the DB work fine.
So, Now the DB is connected. let’s proceed to see how to get data from this New DB.
So, Now to fetch data I am using a helper here which I would say a global file to call this connection through resource connection objection.
In the above code have added the connection name to create connection and get data from custom Database.
Have used \Magento\Framework\App\ResourceConnection to create connection bypassing the connection name that we have created in env.php file
Note: In the above Helper one can also add where condition to fetch data with a filter.
$connection->select()->from( [‘mainTable’ => ‘table_name’])->where(‘id’, ‘xxx’);
So, can be used for different scenario too.
Well, All Done for now.