5

Please give me any example or link for insert and select process without using model in custom module of Magento 2.

asked May 24, 2019 at 5:44

1 Answer 1

2

Try this,

Object Manager :

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
$tableName = $resource->getTableName('employee'); //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.
//Insert Data into table
$sql = "Insert Into " . $tableName . " (emp_id, emp_name, emp_code, emp_salary) Values ('','XYZ','ABD20','50000')";
 $connection->query($sql);
//Update Data into table
$sql = "Update " . $tableName . "Set emp_salary = 20000 where emp_id = 12";
$connection->query($sql);

Di method :

<?php
protected $_resourceConnection;
protected $_connection;
public function __construct(
 \Magento\Framework\App\ResourceConnection $resourceConnection
) {
 $this->_resourceConnection = $resourceConnection;
}
public function getCollection()
{ 
 $selectData = $this->_resourceConnection->getConnection();
 //Your custom sql query
 $query = "SELECT * FROM ( SELECT * FROM TABLE_NAME WHERE customer_id IN ( 0, 5 ) ORDER BY feed_id DESC ) AS t1 GROUP BY position limit 0,5"; 
 $collection = selectData->fetchAll($query);
 return $collection;
}
public function insertQuery(){
 $insertQuery = $this->_resourceConnection->getConnection();
 //Your custom sql query
 $saveQuery = "SELECT * FROM ( SELECT * FROM TABLE_NAME WHERE customer_id IN ( 0, 5 ) ORDER BY feed_id DESC ) AS t1 GROUP BY position limit 0,5"; 
 $save = $insertQuery->fetchAll($query);
}
}

Hope this helps.

answered May 24, 2019 at 5:47
1
  • Thank you. I tried this code's It works Perfectly... Commented May 24, 2019 at 6:08

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.