3

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.

0

3 Answers 3

5

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);
5
  • Hi thanks for quick update, In which file i need to keep above code....
    – balu
    May 19, 2017 at 6:24
  • @balu Follow method-2 if you have not block file. you can use method-2 directly in your product view file. enable path hint and use this code where you want custom table data in phtml. May 19, 2017 at 6:38
  • Did you get your answer? May 19, 2017 at 9:31
  • yes , thank you very much...method 1 i followed, works fine.......
    – balu
    May 19, 2017 at 9:36
  • thanks man. saved me hours of searching :) method 1 works perfect on magento 2.1.8 Sep 13, 2017 at 14:36
2

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..

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.