skip to Main Content

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);
}

5

Answers


  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 MagentoFrameworkModelAbstractModel;
    
    class Data extends AbstractModel
    {   
        protected function _construct()
        {
            $this->_init('<Vendor_Name><Module_Name>ModelResourceModelData');
        }
    }
    

    Step 2: Create ResourceModel file in your custom module

    <?php
    namespace <Vendor_Name><Module_Name>ModelResourceModel;
    
    use MagentoFrameworkModelResourceModelDbAbstractDb;
    
    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>ModelResourceModelData;
    
    
    use MagentoFrameworkModelResourceModelDbCollectionAbstractCollection;
    
    
    class Collection extends AbstractCollection
    {
        protected function _construct()
        {
            $this->_init(
                '<Vendor_Name><Module_Name>ModelData',
                '<Vendor_Name><Module_Name>ModelResourceModelData'
            );
        }
    }
    

    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 MagentoFrameworkViewElementTemplateContext;
    use MagentoFrameworkViewElementTemplate;
    
    use <Vendor_Name><Module_Name>ModelData 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)

    Login or Signup to reply.
  2. 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();

    Login or Signup to reply.
  3. 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 MagentoFrameworkDBAdapterAdapterInterface

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

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

    Login or Signup to reply.
  4. 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 PathToClass;
        
        use MagentoFrameworkAppResourceConnection;
        
        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;
            }
        }
    
    Login or Signup to reply.
  5. I think Magento 2 has support for this in class MagentoFrameworkDBAdapterAdapterInterface. You can create an instance for AdapterInterface by dependency injection or directly by object manager.

    $objectManager = MagentoFrameworkAppObjectManager::getInstance();
    
    /** @var MagentoFrameworkAppResourceConnection $resourceConnection */
    $resourceConnection = $objectManager->get(MagentoFrameworkAppResourceConnection::class);
    
    /** @var MagentoFrameworkDBAdapterAdapterInterface $connection */
    
    $connection = $resourceConnection->getConnection(MagentoFrameworkAppResourceConnection::DEFAULT_CONNECTION);
    
    $sql = "YOUR SELECT QUERY HERE";
    $data = $connection->fetchAssoc($sql);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search