Fetchall() mysql query in Magento 2.

Mysql fetchAll() query using Magento standard way for fetch all the records of the custom query.

You can fetch all the selected record from the table using direct SQL query fetchAll() without worry about the Model operation.

Return Type: fetchAll() always return as array based on your query conditions.

Base Definition of function:

/** 
* @param string|\Magento\Framework\DB\Select $sql An SQL SELECT statement.
* @param mixed $bind Data to bind into SELECT placeholders.
* @param mixed $fetchMode Override current fetch mode.
* @return array
*/
public function fetchAll($sql, $bind = [], $fetchMode = null);

Let’s we are fetching all the record’s from sales_order table, with all the records with status equals to pending.

<?php
namespace Path\To\Class;

use Magento\Framework\App\ResourceConnection;

class fetchAllQuery {

    const ORDER_TABLE = 'sales_order';

    /**
     * @var ResourceConnection
     */
    private $resourceConnection;

    public function __construct(
       ResourceConnection $resourceConnection
    ) {
       $this->resourceConnection = $resourceConnection;
    }

    /**
    * fetchAll Sql Query
    *
    * @return string[]
    */
    public function fetchAllQuery()
    {
      $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->fetchAll($query);
      return $fetchData;
    }
}

Using Fetchall Output is arrays of records from a table.

Array
(
    [0] => Array
        (
            [entity_id] => 1
            [status] => pending
            [grand_total] => 334.9900
        )

    [1] => Array
        (
            [entity_id] => 2
            [status] => pending
            [grand_total] => 69.0000
        )

    [2] => Array
        (
            [entity_id] => 3
            [status] => pending
            [grand_total] => 280.0000
        )
)