Magento 2: How to use the fetchOne() Method with SQL Query

How to use the fetchOne() Method with SQL Query in m2

Hello Magento Friends,

SQL queries in Magento 2 can be extensively employed to tailor and extend platform functions. One common way involves fetching a single value from a database table through the fetchOne() method.

The fetchOne() method is a part of Magento’s database abstraction layer, which provides a consistent way to interact with different database systems. When you execute an SQL query using fetchOne(), it returns the first column of the first row of the result set. If the query doesn’t return any results, it returns null.

Steps to use the fetchOne() Method with SQL Query:

Step 1: Create fetch_record.php file in the Magento root path and then add the below code.

<?php

use Magento\Framework\App\Bootstrap;

try{

  require __DIR__ . ‘/app/bootstrap.php’;

}catch (\Exception $e){

echo ‘Autoload error: ‘ . $e->getMessage();

exit(1);

}

try{

$bootstrap = Bootstrap::create(BP, $_SERVER);

$obj = $bootstrap->getObjectManager();

$state = $obj->get(‘Magento\Framework\App\State’);

$state->setAreaCode(‘frontend’);

$resourceConnection = $obj->get(‘Magento\Framework\App\ResourceConnection’);

$tableName = $resourceConnection->getTableName(‘sales_order’);

$connection = $resourceConnection->getConnection();

$increment_id = ‘000000001’; //Add Your Ordert increment_id

$select = $connection->select()

    ->from([‘c’ => $tableName], [‘*’])

    ->where(“c.increment_id = :increment_id”);

$bind = [‘increment_id’ => $increment_id];

$result = $connection->fetchOne($select, $bind);

if ($result) {

    echo “Fetched value: ” . $result;

} else {

    echo “No record found for Increment Id: ” . $increment_id;

}

}catch(\Exception $e){

    print_r($e->getMessage());

}

Step 2: After adding the above code, run the below URL to check whether the value is fetched or not.

https://yourdomain/fetch_record.php

Conclusion:

Hence, this way you can use the fetchOne() Method with SQL Query. If you have any doubts let me know through the comment section and stay updated with us for more such Magento 2 tutorials.

Happy Coding!

Previous Article

The Shift Toward Cloud-Based Security Solutions

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨