Magento 2, Magento Development, Customization, Extension Development and Integration, Optimization, SEO and Responsive Design

Magento 2, Magento Development, Customization, Extension Development and Integration, Optimization, SEO and Responsive Design

Magento2 – Write Custom Mysql Query In External File

Here we learn how to write custom mysql add, update or delete query in external file

Suppose we have table ’employee’ with fields emp_id, emp_name, emp_code and emp_salary.

use Magento\Framework\App\Bootstrap;
require $_SERVER["DOCUMENT_ROOT"] . '/app/bootstrap.php';
 
$params = $_SERVER;
 
$bootstrap = Bootstrap::create(BP, $params);
$objectManager = $bootstrap->getObjectManager();
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
$tableName = $resource->getTableName('employee'); //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 emp_id = 10";
$connection->query($sql);
 
//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);

Please support us, Like us on Facebook.

  1. Your post is what I need now. Thank you for sharing!

    ReplyDelete
  2. Your post is so useful to me. Thank you!

    ReplyDelete
  3. I truly appreciate this article. Really Cool

    ReplyDelete

 

Copyright @ 2017 HKBlog.