Magento2 – Direct Mysql Query without using model
Posted by navaneeth on Feb 14, 2017 in Magento 2 | No comments yet

In this post we are discussing about the mysql queries in magento2 that we can execute directly without using model
In Magento 1 it uses two resources one for read and another for write, and the scenario in Magento 2 is different, in this we have only one resource connection that can handle both read and write
Here is how we can do it
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager $resource = $objectManager->get('Magento\Framework\App\ResourceConnection'); $connection = $resource->getConnection(); $tableName = $resource->getTableName('sms'); //gives table name with prefix //Select Data from table $sql = "Select * FROM " . $tableName; $result = $connection->fetchAll($sql); // gives associated array, table fields as key in array. //Delete Data from table $sql = "Delete FROM " . $tableName." Where sms_id = 1"; $connection->query($sql); //Insert Data into table $sql = "Insert Into " . $tableName . " (sms_id, destination, message) Values ('','944740850','Test')"; $connection->query($sql); //Update Data into table $sql = "Update " . $tableName . "Set destination = '9447408507' where sms_id = 1"; $connection->query($sql);
This is how we can do Direct Mysql Query without using model in Magento2
Leave a Reply