Excute custom query in magento

Home / Magento / Excute custom query in magento

Magento has provide us very good features for handling or interacting with Database tables. Magento give all the data by default but some time we need to get or insert some custom data.So for this we need to write custom query.

Database Connections In Magento

<?php
// fetch read database connection that is used in Mage_Core module
$read= Mage::getSingleton('core/resource')->getConnection('core_read');

// fetch write database connection that is used in Mage_Core module
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
?>

How to excute custom query in magento

<?php
// fetch read database connection that is used in Mage_Core module
$read= Mage::getSingleton('core/resource')->getConnection('core_read');

$value=$read->query("SELECT ....");
$row = $value->fetch();
 
echo "<pre>";print_r($row);echo "</pre>"; // As Array
 
?>

Insert custom data in magento tabel

<?php 
// fetch write database connection that is used in Mage_Core module
$write = Mage::getSingleton('core/resource')->getConnection('core_write');

// now $write is an instance of Zend_Db_Adapter_Abstract
$write->query("insert into tablename values ('1','demo','data')");
?>

OR you can wite same as below

<?php
$connection = Mage::getSingleton('core/resource')->getConnection('core_write');
// insert
$sql = "INSERT INTO `test_table` (`id`,`name`,`data`) VALUES ('1','demo','data')";
$connection->query($sql);
?>

Related Posts

Leave a Reply

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