Clever works_

How to fetch data from a database and display it in Magento 2

Magento 2 Model

To get information from our table, we need to create a model which extends from AbstractModel. Models are used to connect to the database, and process data from and to it. To create that, we need to prepare a file entitled Data.php in app/code/CleverCode/HelloWorld/Model with the following contents:

We can see that refers to the file Data.php in app/code/CleverCode/HelloWorld/Model/ResourceModel with the following contents:

hello is our table name and id is the primary key in this table. Resource Models are objects that contain code to fetch data from a data store. In the last step we need to create a Collection. We need to create Collection.php in app/code/CleverCode/HelloWorld/Model/ResourceModel/Data with the following contents:

It extends from AbstractCollection. We need to set the path to our Model and Collection. After that we need to modify our block as below:

We need to pass 2 parameters in the constructor. First will be a Magento template element and the second will be our new model. We can see that a new function called getHelloCollection() was added. It returns the collection from our table. We used a function called getCollection(). Its function is from Magento AbstractModel class. It has more functions to delete, save, load, set and get data.

Magento 2 GET DATA FROM CUSTOM TABLE IN .PHTML FILE

To show information from a table we need to change our phtml file like this:

Instead of $this we can use $block. A variable called $item is the element of our model, and by using magic functions we can get all the data. We should see the content of our table like this:

Clever Code Page

Related works_

BreakAwayDistributing B2B and B2C
selling platform

The SLK Solutions agency responsible for developing an online store hired us to help them with creating a selling platform dedicated to B2B and B2C clients. BreakAwayDistributing – agency operating from 1993 with main office located in Hamilton, Canada offers high quality products

Learn more

Internet flower shop
from SLK Solutions

SLK Solutions is an IT agency operating in the USA, which helps small and large business owners to implement new technologies. They asked us to support them with our experts with the complete implementation of an eCommerce project for their client.

Learn more