Magento 2.0 – Programmatically Get the Prefix Used for Tables

magento-2.0magento2prefix

I am doing some raw sql opertaions and would like to know if there is a way to get programmatically the Prefix used for the tables (the prefix you set during the Magento installation)?

Best Answer

You can get the prefix by using the function getTableName() like below : Always use getTableName with raw queries to fetch the table along with the prefix dynamically

 protected $_resource;

 public function __construct(
    \Magento\Backend\App\Action\Context $context,
    \Magento\Framework\App\ResourceConnection $resource
    ) {
    $this->_resource = $resource;
    parent::__construct($context);
}
    
public function execute()
{
    
    $connection  = $this->_resource->getConnection();
    $tableName   = $this->_resource->getTableName('tablename_without_prefix'); // It will return table with prefix

    $mapsDeleteQuery = "your raw SQL Query";
    $connection->query($mapsDeleteQuery);
}

You can also get the prefix from the file app/etc/env.php

'db' => 
  array (
    'table_prefix' => '', // if any prefix is used, you can see here
    'connection' => 
    array (
      'default' => 
      array (
        'host' => 'localhost',
        'dbname' => 'magento2',
        'username' => 'abc',
        'password' => 'abc',
        'active' => '1',
      ),
    ),
  ),
Related Topic