This is the blog for getting Idea regarding PHP, Magento, jQuery and JavaScript for Customization.

Wednesday 5 October 2016

Magento 2 : Method to use SQL query

Hello Friends,

         Magento 2.X is use Resource Connection Method for fetch data from the Database, Which is little bit different from the Magento 1.X

        I have used code like below, and I hope it will helps to you also,

        Here, I show the code for SELECT query for magento2

 1)  $this->_resources= \Magento\Framework\App\ObjectManager::getInstance()
->get('Magento\Framework\App\ResourceConnection');
 2)  $connection = $this->_resources->getConnection();
 3)  $Table_Name = $this->_resources->getTableName('TABLE NAME');
4) $data = $connection->fetchAll('SELECT * FROM '.$Table_Name.' WHERE
Field_Name=Value');

       you just copy & paste this in related *.phtml or Controller files !

       If you want to use Insert or Update then just replace Select query, and it will work !

       For, Insert replace line number (4)

4) $data = $connection->fetchAll('INSERT into '.$Table_Name.'
VALUES ('value1','value2');

       For, Update replace line number (4)

4) $data = $connection->fetchAll('UPDATE '.$Table_Name.'
SET column1=value1,column2=value2 WHERE id=1;

This is working fine for me in Magento 2.0 !
       

No comments:

Post a Comment