Skip to content

Magento2 : Custom Sql Directive

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
$tableName = $resource->getTableName('your_table_name');
 
//Select Data from table
$sql = "Select * FROM " . $tableName;
$result = $connection->fetchAll($sql); 

/*

example result 
Array
(
    [0] => Array
        (
            [user_id] => 121212
            [name] => ABC motor
           
        )
		
	[1] => Array
        (
            [user_id] => 44534
            [name] => DEF motor
           
        )

)
			

*/

//Select Data from table
$sql = "Select * FROM " . $tableName;
$result = $connection->fetchOne($sql); 

/*

example result :

121212
			

*/

//Select Data from table
$sql = "Select * FROM " . $tableName;
$result = $connection->fetchRow($sql); 

/*

example result 
Array
(  [user_id] => 121212
   [name] => ABC motor
)
			

*/ 
//query  table
$sql = "Delete FROM " . $tableName." Where id = 123";
$connection->query($sql);

 

Comments are closed.