Proper way to select data from Magento2 Databases

ubakara samy picture ubakara samy · Oct 24, 2017 · Viewed 12.5k times · Source

I have created a PHP function to display data from database,
and i'm triyng to include it in my megento2 block function,

here is my code for Select data

$dates = date("Y-m-d");
$phone = $_POST["phone"];

 $sql = "SELECT * FROM otpp WHERE phone = '$phone' AND dates = '$dates'";

    $result = mysqli_query($conn, $sql);
    $count = mysqli_num_rows($result);
    // if exists ?
    if ($count > 0) {

        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();
            $otppass = $row["otp"];
            echo $otppass;
        } else {
            echo "0 results";
   }

Can I Proceed with this way to get datas from database or any other ways use datas from databases?

Answer

ubakara samy picture ubakara samy · Apr 17, 2018

Magento2 has an object-oriented way to utilize data from Database . That models and collections

Step 1 create a model

<?php
namespace <CompanyName>\<ModuleName>\Model;

use Magento\Framework\Model\AbstractModel;

    class Data extends AbstractModel
    {   
        protected function _construct()
        {
            $this->_init('<CompanyName>\<ModuleName>\Model\ResourceModel\Data');
        }
    }

Step 2 Creat Resource model

<?php

namespace <CompanyName>\<ModuleName>\Model\ResourceModel;


use \Magento\Framework\Model\ResourceModel\Db\AbstractDb;

class Data extends AbstractDb
{
    protected function _construct()
    {
        $this->_init('TableName', 'id'); //id is a primary key 
    }
}

Step 3 Create Collection

namespace <CompanyName>\<ModuleName>\Model\ResourceModel\Data;


use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;


class Collection extends AbstractCollection
{
    protected function _construct()
    {
        $this->_init(
        '<CompanyName>\<ModuleName>\Model\Data',
        '<CompanyName>\<ModuleName>\Model\ResourceModel\Data'
    );
    }
}

Step 4 then we can simply use this collection in our block file

namespace <CompanyName>\<ModuleName>\Block;


use Magento\Framework\View\Element\Template\Context;
use <CompanyName>\<ModuleName>\Model\Data;
use Magento\Framework\View\Element\Template;


class Hello extends Template
{

    public function __construct(Context $context, Data $model)
    {
                $this->model = $model;
        parent::__construct($context);

    }


    public function getDatas()
    {
        $Datas = $this->model->getCollection();
        return $Datas;
    }

}