'conversion of magento 1 into magento 2

I was using fetch_assoc() method in magento 1 . I want to convert it into Magento 2 . there is no fetch_assoc() method in magento 2.

if(is_object($result))
{   
    while ($resultsArray =$result->fetch_assoc())
    {
        if(empty($data))
        {
           $data[] = array_keys($resultsArray);
        }
        $data[] = $resultsArray;

    } var_dump($data);
}


Solution 1:[1]

I'm not sure my proposed solution is useful for you or not but the best approach to fetch data in Magento 2 is based on Models and Collections.

Step 1: Firstly, you have to create a Model file in your module

<?php
namespace <Vendor_Name>\<Module_Name>\Model;

use Magento\Framework\Model\AbstractModel;

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

Step 2: Create ResourceModel file in your custom module

<?php
namespace <Vendor_Name>\<Module_Name>\Model\ResourceModel;

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

class Data extends AbstractDb
{
    protected function _construct()
    {
        // Second parameter is a primary key of the table
        $this->_init('Table_Name', 'id'); 
    }
}

Step 3: Create Collection file to initialize Model and ResourceModel files.

namespace <Vendor_Name>\<Module_Name>\Model\ResourceModel\Data;


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


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

Step 4: Last thing that you need to do is create a Block file in the same module and utilize collection, something like this:

namespace <Vendor_Name>\<Module_Name>\Block;

use Magento\Framework\View\Element\Template\Context;
use Magento\Framework\View\Element\Template;

use <Vendor_Name>\<Module_Name>\Model\Data as DataCollection;

class Custom_Module extends Template
{
    protected $dataCollection;

    public function __construct(Context $context, DataCollection $dataCollection)
    {
        $this->_dataCollection = $dataCollection;
        parent::__construct($context);
    }

    public function getDataCollecton()
    {
        $collection = $this->_dataCollection->getCollection();
        return $collection;
    }
}


Another Solution

You can also use fetchAll instead of fetch_assoc() in Magento 2, if you don't want to implement models and collections based solution, something like this:

// Select Data from table
$sql = "Select * FROM " . $tableName;
$result = $connection->fetchAll($sql);

and for reference, you can also have a look into Magento2 – Write Custom Mysql Query (Without Using Model)

Solution 2:[2]

I think we can use something like below :

    $adapter = $this->resourceConnection->getConnection($resource);        
    $stmt = $adapter->query($sql);

    // Use FETCH_NUM so we are not dependent on the CASE attribute of the PDO connection
    $results = $stmt->fetchAll(\Zend_Db::FETCH_ASSOC);

Or if we have $connection instanceof \Magento\Framework\DB\Adapter\AdapterInterface

    $connection->fetchAll($sql, $binds, \PDO::FETCH_ASSOC);

By using those, i think you're gonna get the same result to magento 1 fetch_assoc

Solution 3:[3]

Alternative of the fetch_assoc() in magento 2 is fetchAssoc($SQL_QUERY)

Below is the example.

For get order where status is pending data using fetchAssoc(SQL_QUERY)

<?php
    namespace Path\To\Class;
    
    use Magento\Framework\App\ResourceConnection;
    
    class fetchAssoc {
    
        const ORDER_TABLE = 'sales_order';
    
        /**
         * @var ResourceConnection
         */
        private $resourceConnection;
    
        public function __construct(
           ResourceConnection $resourceConnection
        ) {
           $this->resourceConnection = $resourceConnection;
        }
    
        /**
        * fetchAssoc Sql Query
        *
        * @return string[]
        */
        public function fetchAssocQuery()
        {
          $connection  = $this->resourceConnection->getConnection();
          $tableName = $connection->getTableName(self::ORDER_TABLE);
    
          $query = $connection->select()
            ->from($tableName,['entity_id','status','grand_total'])
            ->where('status = ?', 'pending');
    
          $fetchData = $connection->fetchAssoc($query);
          return $fetchData;
        }
    }

Solution 4:[4]

In magento 2 you can use same but for that you need to create database connection. I suggest you to use resource or collection models to get the result and if you want to get the first row in object format then you should use getFirstItem();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Adeel
Solution 2 ThuanDoan
Solution 3 Dharman
Solution 4 Dharman