Friday, September 9, 2011

Magento How to run SQL anywhere

Magento is a bit complex. Sometime it takes so much time to find the existing model on Magento to retrieve data with complex query. So you will think about how to run SQL anywhere you want. Please check the below code to find the solution
01
02
03
04
05
06
07
08
09
10
$db = Mage::getModel('core/resource')->getConnection('core_write');
$table_prefix = Mage::getConfig()->getTablePrefix();
$result = $db->query("SELECT `entity_id` FROM `{$table_prefix}catalog_product_entity`");
if(!$result) {
    return false;
}
 
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
    print_r($row); // process the row data here
}
Reference: at class Zend_Db
Controls how the next row will be returned to the caller. This value must be one of the PDO::FETCH_* constants, defaulting to value of PDO::ATTR_DEFAULT_FETCH_MODE (which defaults to PDO::FETCH_BOTH).
  • PDO::FETCH_ASSOC: returns an array indexed by column name as returned in your result set
  • PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0-indexed column number as returned in your result set
  • PDO::FETCH_BOUND: returns TRUE and assigns the values of the columns in your result set to the PHP variables to which they were bound with the PDOStatement::bindColumn() method
  • PDO::FETCH_CLASS: returns a new instance of the requested class, mapping the columns of the result set to named properties in the class. If fetch_style includes PDO::FETCH_CLASSTYPE (e.g. PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE) then the name of the class is determined from a value of the first column.
  • PDO::FETCH_INTO: updates an existing instance of the requested class, mapping the columns of the result set to named properties in the class
  • PDO::FETCH_LAZY: combines PDO::FETCH_BOTH and PDO::FETCH_OBJ, creating the object variable names as they are accessed
  • PDO::FETCH_NUM: returns an array indexed by column number as returned in your result set, starting at column 0
  • PDO::FETCH_OBJ: returns an anonymous object with property names that correspond to the column names returned in your result set
Checked at:
  • Magento 1.5.1

No comments:

Post a Comment