How get custom Table Data in phtml file without creating Model file. Magento 2
-
09-10-2020 - |
Question
I created custom table in my database through phpmyadmin, now I want display top1 record from that table on home page, and top2,top3 records need to display in product details page.
Solution
You can get your custom table data by following way
Method - 1: By using Factory Method
<?php
protected $_connection;
public function __construct(
.....
\Magento\Framework\App\ResourceConnection $resource
.....
) {
$this->_connection = $resource->getConnection();
}
public function getTableData()
{
$myTable = $this->_connection->getTableName('table_name');
$sql = $this->_connection->select()->from(
["tn" => $myTable]
);
$result = $this->_connection->fetchAll($sql);
return $result;
}
Then you can get your custom table data in phtml file
$myTableData = $this->getTableData();
print_r($myTableData);
Method - 2: By using objectManager
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
$tableName = $resource->getTableName('your_table'); //gives table name
//Select Data from table
$sql = $connection->select()->from(
["tn" => $tableName]
);
$result = $connection->fetchAll($sql);
print_r($result);
OTHER TIPS
In this case, you should create a custom model for this custom Table.
Follow this https://www.softprodigy.com/store/article/create-model-and-collection-for-custom-table-in-magento2/ for reference.
In this this you should declare Model, Resource Model , Collection class..
You have to create block and template. And create a layout in to make a link between block.php and template.php. then using $block object you can call block method.