While Magento 2 installation, You get the option to set the database prefix for the Magento 2 tables. Keeping the default table names makes it easier for hackers to attack. Using database prefix adds the layer of the security which restricts the attack of the generic SQL injection attacks.
Now, when you call the table to fetch the value it holds in some custom extension, you require to get table name with prefix in Magento 2 to get the correct value without showing the table not found error. To achieve this, you need to enable the ‘Show Prefix Field‘ option in your database configuration file.
Apart from enabling the ‘Show Prefix Field’ option in the database configuration file, it is also essential to show Tax/VAT Number in Registration Form, which can assist in accurate tax calculations and prevent errors during transactions.
Today, I have come up with the solution to get table name with prefix in Magento 2 so that you can call the prefixed table name without getting any issue!
The solution to Get Table Name with Prefix in Magento 2
Suppose, your table name has mt_ prefix and you want to get the table name with the prefix in Magento 2 block file:
<?php namespace Vendor\Extension\Block; use Magento\Framework\App\ResourceConnection; use Magento\Framework\View\Element\Template; class View extends Template { protected $resource; public function __construct( ResourceConnection $resource ) { $this->resource = $resource; } public function getTableName() { $connection = $this->resource->getConnection(); $tableName = $connection->getTableName('quote'); // returns "mt_quote" } }
Using the above code, you can get table name along with the prefix. For example, if your table has a prefix as mt_ , you will get the table name value as mt_quote.