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
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
andCollections
.Step 1: Firstly, you have to create a
Model
file in your moduleStep 2: Create
ResourceModel
file in your custom moduleStep 3: Create
Collection
file to initializeModel
andResourceModel
files.Step 4: Last thing that you need to do is create a
Block
file in the same module and utilize collection, something like this:Another Solution
You can also use
fetchAll
instead offetch_assoc()
in Magento 2, if you don’t want to implementmodels
andcollections
based solution, something like this:and for reference, you can also have a look into Magento2 – Write Custom Mysql Query (Without Using Model)
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();
I think we can use something like below :
Or if we have $connection instanceof MagentoFrameworkDBAdapterAdapterInterface
By using those, i think you’re gonna get the same result to magento 1 fetch_assoc
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)
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.