Skip to main content

Magento2 custom Sql query



<?php

/*
Following are the methods which can be used to retrieve data $connection object
fetchAll - fetch all records based on query
fetchRow - fetch single row
fetchAssoc - fetch result with column names
fetchCol - fetch single column
fetchOne - fetch first record
*/

// save this file on magento2 root and customize for your needs

use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';

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

$objectManager = $bootstrap->getObjectManager();


$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();


$sql = "SELECT * FROM ".$resource->getTableName('core_config_data');
$result = $connection->fetchAll($sql);
echo '<pre>';
print_r($result);

//Insert query
$sql = "INSERT INTO ".$resource->getTableName('TABLENAME')." SET columnname='value'" ;
$connection->query($sql);


Comments