How to Fetch Update data using Direct Sql query in phtml file In Magento 2.1.3..

  • 3
    It's a bad idea to execute SQL directly in a view file, it would be better to fetch needed data in block class via some service or model, and call block method in the view file.
    – joni jones
    Jan 27, 2017 at 14:39
  • 1
    I don't know who down vote my answer. Some developer want's to know how to do that but they don't use it.
    – Sohel Rana
    Jan 27, 2017 at 15:00
  • 2
    Suppose, it's a bad practice to give answers on obviously the wrong approach.
    – joni jones
    Jan 27, 2017 at 15:32

1 Answer 1


Try following way:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
$sql = 'select * from customer_grid_flat';
$data = $connection->fetchAll($sql);
echo '<pre>';print_r($data);

NB: Always call block method and DI for creating model/repository object for fetching data.


Not the answer you're looking for? Browse other questions tagged or ask your own question.