Oh snap! You are using an old version of browser. Update your browser to get new awesome features. Click for more details.

Magento 2 How to get the database(connection) details


If you required database detail in your custom file. This article help to how get the database details from env.php file. In your block file add below code and simply call function anywhere.


<?php
namespace Namespace\Modulename\Block;

use Magento\Framework\App\DeploymentConfig\Reader;

class Index extends \Magento\Framework\View\Element\Template
{
private $deploymentConfigReader;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        Reader $deploymentConfigReader
    ) {
    parent::__construct($context);
    $this->deploymentConfigReader = $deploymentConfigReader;
    }

    public function getDbConnection()
    {
        try {
            $deploymentConfig = $this->deploymentConfigReader->load();
            $DBdata = $deploymentConfig['db']['connection']['default'];

            echo 'host: ' . $DBdata['host'];
            echo ' username: ' . $DBdata['username'];
            echo ' password: ' . $DBdata['password'];
            echo ' dbname: ' . $DBdata['dbname'];
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }
}

(0) comments