LinkedIn Twitter RSS Reset

Using Custom Query in Magento

Magento has given us very good features to manage Models and Collection for interacting with Database tables. Nowonder, they are very helpful in most of the cases. Yet, we may need to write custom query in some cases (if you need it quick or if you are new to Models & Collection in Magento). But by Magento’s standard this is not recommended. If you are a starter you may find this quering to database very helpful. Here is how you can do this.

The idea is simply to get the core connection object and use its functions to run your query.

<?php
// For Read

// fetch read database connection that is used in Mage_Core module
$read= Mage::getSingleton('core/resource')->getConnection('core_read');
$value=$read->query("SE...");
$row = $value->fetch();

print_r($row); // As Array

// For Write

// 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 ('aaa','bbb','ccc')");

?>

3 Responses to “Using Custom Query in Magento”

  1. August 2, 2010 at 6:53 am #

    Very informative blog. I like your blog because of unique content. thanks for sharing such a useful information.

Trackbacks/Pingbacks

  1. Custom Query In Magento a Zend Approach | Subesh Pokhrel's Blog - Magento Development Tips - August 4, 2011

    [...] already mentioned about custom query in Magento, before but now I think its time to upgrade that method to next level because it would always be [...]

  2. Custom Query In Magento a Zend Approach | Magento News - August 4, 2011

    [...] already mentioned about custom query in Magento, before but now I think its time to upgrade that method to next level because it would always be [...]

Leave a Comment