Queries in Magento

I am describing here the method for executing custom MySQL queries in Magento.

<?php
   //select query
   $read = Mage::getSingleton('core/resource')->getConnection('core_read'); 
//make connection
    $qry = "select name FROM user_data WHERE id=1 LIMIT 1 "; //query            
    $res = $read->fetchRow($qry); //fetch row
    $name = $res['name']; //outputs name
  
    //other form
    $qry = "select name FROM user_data WHERE namer LIKE '%a%' ";//query            
    $res = $read->fetchAll($qry); //get array

    //Insert query
    $write =  Mage::getSingleton('core/resource')->getConnection('core_write');
    $sql  = "INSERT INTO user_data values (?,?)"; //insert query
    $write->query($sql, array('name','pass')); //write to database
    
?>

8 thoughts on “Queries in Magento

  1. Dear,

    I am using this same functionality but now working.
    My file path:

    app/design/frontend/base/default/template/email/order/item.phtml

    $orderPresId = $_order->getIncrementId();
    $resource = Mage::getSingleton(‘core/resource’);
    $readConnection = $resource->getConnection(‘core_read’);
    $query = “SELECT * FROM entry WHERE orderid = “.$orderPresId.” LIMIT 0,1″;
    $resultPres =$readConnection->query($query);
    //$rows = $resultPres->fetch();
    //$rows = $resultPres->fetch(PDO::FETCH_ASSOC);
    echo “”;print_r($resultPres);

    1. Please first check whether the data exists or not in DB by manually executing the query. Also for read you can directly do like $readConnection->fetchRow($query)

  2. Is there also something for update query?
    Or is $write->query() can do that anyway

Leave a Reply to irlsolutioner Cancel reply

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

Scroll to top