Reading list Switch to dark mode

    Magento2 – Write Custom Mysql Query (Without Using Model)

    Updated 16 February 2023

    Here we learn how to write custom mysql query in Magento2.

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

    Now use following code snippet to run custom queries in magento2 without using model.

    Custom Mysql Query

    			$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager
    			$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.
    
    			//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);

    Searching for an experienced
    Magento 2 Company ?
    Find out More
    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    8 comments

  • Pranab Natta
    • Webkul Support
  • @limonazzo
  • Shoaib Munir
    • Webkul Support
  • Raj Kumar
  • Sachin S
  • sbckarthi
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home