Magento – Fetch data from database custom table

databaseee-2.2.5frontend

I have created a new table 'custom_table' i need to render the values in a custom template.
How to get the values of that table ?

Best Answer

Render the values from custom table in a custom template, Follow bellow steps.

Create Model and ResourceModel in your custom module for collection to get the table's data.

/Your_Magento/app/code/Test/Welcome/Model/Welcome.php

<?php
namespace Test\Welcome\Model;

class Welcome extends \Magento\Framework\Model\AbstractModel
{
    public function _construct()
    {
        $this->_init('Test\Welcome\Model\ResourceModel\Welcome');
    }
}

/Your_Magento/app/code/Test/Welcome/Model/ResourceModel/Welcome.php

<?php
namespace Test\Welcome\Model\ResourceModel;

class Welcome extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
    public function _construct()
    {
        $this->_init('test_welcome_welcome', 'id');
    }
}

/Your_Magento/app/code/Test/Welcome/Model/ResourceModel/Welcome/Collection.php

<?php
namespace Test\Welcome\Model\ResourceModel\Welcome;

class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection 
{
    protected function _construct()
    {
        $this->_init('Test\Welcome\Model\Welcome','Test\Welcome\Model\ResourceModel\Welcome');
    }
}

/Your_Magento/app/code/Test/Welcome/view/frontend/templates/view.phtml

<?php
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $model=$objectManager->create('Test\Welcome\Model\Welcome');
    $datacollection=$model->getCollection();

    echo "<table border=1><tr align=center><th>Id</th><th>Fist Name</th><th>Last Name</th></tr>";
    foreach ($datacollection as $data) {
        echo "<tr align=center>";
            echo "<td>".$data->getId()."</td>";
            echo "<td>".$data->getFirstname()."</td>";
            echo "<td>".$data->getLastname()."</td>";
        echo "</tr>";
    }
    echo "</table>";
?>

You can also get data from block using factory method, Calling block from phtml $datacollection = $block->getCollection();

I hope this will useful for you.:)