Write a fetchRow direct mysql query in Magento 2.

Write a Mysql fetchRow() query using Magento standard way for fetches the first row of the SQL result as an output.

You can get the first row as a result from the list of a resultant array using query.

Direct SQL query fetchRow() without worrying about the Model operation.

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

Base Definition of function:

     /**
     * Fetches the first row of the SQL result.
     *
     * Uses the current fetchMode for the adapter.
     *
     * @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 fetchRow($sql, $bind = [], $fetchMode = null);

Let’s we are fetching the first row from sales_order table.

<?php
namespace Path\To\Class;

use Magento\Framework\App\ResourceConnection;

class FetchRow {

    const ORDER_TABLE = 'sales_order';

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

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

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

We are fetching the first row from the sales_order table with Order status is pending.

The output is the first row of the SQL result as an array.

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

 

Check for other Direct Sql Query in Magento 2