How to Get Table Name with Prefix in Magento 2
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?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.
Let me know in what custom extension or functionality, you used the above code to get the prefixed table name. Don’t forget to ask your questions and queries in the comment section below and I would be happy to help. 🙂
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
Prev
Magento 2.3.4: What’s New in Latest Magento 2.3.4 [January 2020]
How to Get Store Information on Magento 2 Checkout Page by Knockout Js
Next