<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Subesh Pokhrel&#039;s Blog - Magento Development Tips &#187; String</title>
	<atom:link href="http://subesh.com.np/tag/string/feed/" rel="self" type="application/rss+xml" />
	<link>http://subesh.com.np</link>
	<description>PHP &#38; Magento Tips and Tutorials</description>
	<lastBuildDate>Tue, 20 Mar 2012 18:15:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Custom Query In Magento a Zend Approach [Updated]</title>
		<link>http://subesh.com.np/2011/08/custom-query-in-magento-a-zend-approach/</link>
		<comments>http://subesh.com.np/2011/08/custom-query-in-magento-a-zend-approach/#comments</comments>
		<pubDate>Thu, 04 Aug 2011 10:11:05 +0000</pubDate>
		<dc:creator>Subesh Pokhrel</dc:creator>
				<category><![CDATA[Magento]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[Query]]></category>
		<category><![CDATA[String]]></category>
		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://subesh.com.np/?p=300</guid>
		<description><![CDATA[I&#8217;ve 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 good to have standard code for reference.So it is just a new improved way of using a custom query. First of all we will need is a connection [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve already mentioned about<a href="http://subesh.com.np/2009/12/using-custom-query-in-magento/"> custom query in Magento</a>, before but now I think its time to upgrade that method to next level because it would always be good to have standard code for reference.So it is just a new improved way of using a custom query.<br />
First of all we will need is a connection instance. Lets use default_setup instance because it can used for read and write purpose.</p>
<pre class="brush: php; title: ; notranslate">
$connection = Mage::getSingleton('core/resource')-&gt;getConnection('default_setup');
</pre>
<p>Then we will use this connection to instanciate Zend_Db_Select object and write query like</p>
<pre class="brush: php; title: ; notranslate">
$select = new Zend_Db_Select($connection);
$table = 'catalog_product_index_price';
$select-&gt;from($table, array('entity_id'))
	-&gt;where('entity_id = ?', $entityId);

// Getting result

$result = $select-&gt;query();
$rowCount = $result-&gt;rowCount();

if ($rowCount) {
	foreach ($result-&gt;fetchAll() as $data) {
		return $data['entity_id'];
	}
}
</pre>
<p>The above one is for select but what about inserting data? It is simple as well. All you have to do is create an associative array of data to be inserted and use connection to add data. For example</p>
<pre class="brush: php; title: ; notranslate">
$connection = Mage::getSingleton('core/resource')-&gt;getConnection('default_setup');
$table = 'catalog_product_index_price';

$insertData = array();
$insertData ['price'] = $productPrice;
$insertData ['final_price'] = $productPrice;
$insertData ['min_price'] = $productPrice;
$insertData ['max_price'] = $productPrice;
$insertData ['tier_price'] = $productPrice;

$connection-&gt;insert($table, $insertData);
</pre>
<p>I think this should be a good enough code for using custom query in Magento. About Zend_Db_Select please visit <a href="http://framework.zend.com/manual/en/zend.db.select.html">http://framework.zend.com/manual/en/zend.db.select.html</a>.</p>
<p><strong>[UPDATE]</strong></p>
<p>If you want to update the data with custom query and have a condition then you can send the conditions as array as third params to update function. For example.</p>
<pre class="brush: php; title: ; notranslate">
$connection = Mage::getSingleton('core/resource')-&gt;getConnection('default_setup');
$table = 'catalog_product_index_price';

$updateCond = array(); // Update condition array container.
$insertData = array();
$insertData ['price'] = $productPrice;
$insertData ['final_price'] = $productPrice;
$insertData ['min_price'] = $productPrice;
$insertData ['max_price'] = $productPrice;
$insertData ['tier_price'] = $productPrice;

$updateCond [] = 'store_id = 0';
$updateCond [] = 'entity_id = 3';

$connection-&gt;insert($table, $insertData, $updateCond);
</pre>
<p>Happy Brogramming!!</p>
]]></content:encoded>
			<wfw:commentRss>http://subesh.com.np/2011/08/custom-query-in-magento-a-zend-approach/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Analysis &amp; Usage of Collections in Magento</title>
		<link>http://subesh.com.np/2010/05/analysis-usage-collections-magento/</link>
		<comments>http://subesh.com.np/2010/05/analysis-usage-collections-magento/#comments</comments>
		<pubDate>Thu, 13 May 2010 12:20:25 +0000</pubDate>
		<dc:creator>Subesh Pokhrel</dc:creator>
				<category><![CDATA[Magento]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[Query]]></category>
		<category><![CDATA[String]]></category>

		<guid isPermaLink="false">http://subesh.com.np/?p=246</guid>
		<description><![CDATA[As a Magento Programmer I am fascinated by the use &#38; simplicity of collection used in Magento. Simplicity, does not really mean being simple (it is rather complex structured) but easy to use. With the help of one of my colleague, I got down to understand how collection really represents the &#8220;collection&#8221; of data we [...]]]></description>
			<content:encoded><![CDATA[<p>As a Magento Programmer I am fascinated by the use &amp; simplicity of collection used in Magento. Simplicity, does not really mean being simple (it is rather complex structured) but easy to use. With the help of one of my colleague, I got down to understand how collection really represents the &#8220;collection&#8221; of data we are actually trying to get from database. Here is what I found drilling down into the Magento&#8217;s Core. I may be &#8220;not quite right&#8221; with the analysis, you can always comment.</p>
<p>Almost all the collections found inside  <strong>app/code/codepool/Namespace/Module/Model/Mysql4/model/Collection.php</strong> are the child of parent Class <strong>Mage_Core_Model_Mysql4_Collection_Abstract</strong>. Primary thing done in the class constructor is initializing its resource and Model. If you look into one of the Collection class you can see in its constructor.</p>
<pre class="brush: php; title: ; notranslate">
/**
	 * @class Mage_Checkout_Model_Mysql4_Agreement_Collection
     * Initialize resource
     *
     */
    protected function _construct()
    {
        $this-&gt;_init('checkout/agreement');
    }
</pre>
<p>And this _init function has been implemented in its parent class as</p>
<pre class="brush: php; title: ; notranslate">
/**
     * Standard resource collection initalization
     *
     * @param string $model
     * @return Mage_Core_Model_Mysql4_Collection_Abstract
     */
    protected function _init($model, $resourceModel=null)
    {
        $this-&gt;setModel($model);
        if (is_null($resourceModel)) {
            $resourceModel = $model;
        }
        $this-&gt;setResourceModel($resourceModel);
        return $this;
    }
</pre>
<p>The resource class can be found in <strong>app/code/codepool/Namespace/Module/Model/Mysql4/model.php</strong>. And this resource class in turn initializes the database table to be used in the Module along with the table&#8217;s primary key.</p>
<pre class="brush: php; title: ; notranslate">
class Mage_Checkout_Model_Mysql4_Agreement extends Mage_Core_Model_Mysql4_Abstract
	{

	protected function _construct()
    {
        $this-&gt;_init('checkout/agreement', 'agreement_id');
    }
	......
	}
</pre>
<p>It is this resource class that actually works out the database connections, read/write adapters and performs transactions. So this is the basic deduction about the link of collection with the database and its tables. But how are those collection formed still remains a mystery, not anymore! In this section of the post I will try to explain how are the collections really formed.</p>
<p>If I can, &#8220;<strong>collection</strong>&#8221; can be defined as collection or array of its resource. And in Magento case, most of the resources are database&#8217;s query results. Simply you can visualize &#8220;<strong>collection</strong>&#8221; to be array of your model&#8217;s resource. If a &#8220;<strong>query</strong>&#8221; in Magento returns a collection of all the products then it would mean that the very collection is an array of all the individual product&#8217;s object. But one question still remains how will the database query&#8217;s result transform into a Magento &#8220;<strong>collection</strong>&#8220;. To understand that we need to understand the collection class and its parents.</p>
<p>The class Structure for <strong>Mage_Core_Model_Mysql4_Collection_Abstract</strong> is like this.</p>
<p>Mage_Core_Model_Mysql4_Collection_Abstract</p>
<p style="padding-left: 30px;">|__ Varien_Data_Collection_Db (C)</p>
<p style="padding-left: 60px;">|__	Varien_Data_Collection (C)</p>
<p style="padding-left: 90px;">|__ IteratorAggregate (I)</p>
<p style="padding-left: 90px;">|__ Countable (I)</p>
<p>You can see that all collection implements two Interfaces <strong>IteratorAggregate </strong>&amp; <strong>Countable</strong>.</p>
<p><a href="http://goo.gl/MjAT" target="_blank">IteratorAggregate </a> is predefined in Standard PHP Library that extends Abstract Base Class <a href="http://goo.gl/rzXS" target="_blank">Traversable </a>. On using this Interface you can then <a href="http://goo.gl/hgtI" target="_blank">Iterate Through Object</a> using &#8220;<strong>foreach</strong>&#8221; construct. Countable returns the size of the Collection Object.</p>
<p>Among the two Interfaces, <strong>IteratorAggregate </strong>is particularly important. As you can see in Class Hierarchy both the interfaces are implemented by<strong> Varien_Data_Collection</strong> concrete class. <strong>IteratorAggregate</strong> has abstract public method <strong>getIterator()</strong> which returns the Iterator interface and the concrete Class has to implement the method on its own. It is this Iterator that provides the real iteration functionality. You can get a detailed description about Iterator <a href="http://goo.gl/C9Nx" target="_blank">Here</a>.</p>
<p>So if you look into the <strong>Varien_Data_Collection</strong> you will find the <strong>getIterator()</strong> implemented like this.</p>
<pre class="brush: php; title: ; notranslate">
/**
	 * @class Varien_Data_Collection
     * Implementation of IteratorAggregate::getIterator()
     */
    public function getIterator()
    {
        $this-&gt;load();
        return new ArrayIterator($this-&gt;_items);
    }
</pre>
<p>As you can see that it first loads the &#8220;<strong>items</strong>&#8221; (I will get back to this Items) and instanciates the value to an internal Class <a href="http://goo.gl/8LAi" target="_blank">ArrayIterator </a>. And the Iterator returned by this function can then be iterated using <strong>foreach </strong>construct.</p>
<p>Looks like it is going to be a looonnnnng post, let be summarize what I&#8217;ve tried to point out until now. I&#8217;ve tried to show the link between the collection class or rather object with the database table and explain the iteration behavior of the collection object. But one question still remains how will the database query&#8217;s result transform into a Magento&#8217;s &#8220;<strong>collection</strong>&#8220;. This is where the &#8220;<strong>items</strong>&#8221; explanation need to be done.</p>
<p>&#8220;<strong>Items</strong>&#8221; are actually array if individual object (item) of the collection which represents the array of tuple of the database query result. As you see in the snippet above the <strong>ArrayIterator </strong>takes <strong>$this-&gt;_items</strong> are parameter. But <strong>$this-&gt;_items</strong> are not populated here on <strong>Varien_Data_Collection</strong> but rather on is child class <strong>Varien_Data_Collection_Db</strong>. Here&#8217;s the snippet from Varien_Data_Collection_Db.</p>
<pre class="brush: php; title: ; notranslate">
/**
     * Load data
     * @class Varien_Data_Collection_Db
     * @return  Varien_Data_Collection_Db
     */
    public function load($printQuery = false, $logQuery = false)
    {
        if ($this-&gt;isLoaded()) {
            return $this;
        }

        $this-&gt;_renderFilters()
             -&gt;_renderOrders()
             -&gt;_renderLimit();

        $this-&gt;printLogQuery($printQuery, $logQuery);

		// Getting Data from DB
        $data = $this-&gt;getData();

        $this-&gt;resetData();

        if (is_array($data)) {

		    // Looping on each result row
            foreach ($data as $row) {
			    // Creating Empty &quot;item&quot; Varien_Object's object
                $item = $this-&gt;getNewEmptyItem();

                if ($this-&gt;getIdFieldName()) {
                    $item-&gt;setIdFieldName($this-&gt;getIdFieldName());
                }

				// Setting Varien_Object's values to that of the row
                $item-&gt;addData($row);

				/**
				* Adding the &quot;item&quot; to the collection @class Varien_Data_Collection
				* So while referring to $this-&gt;_items @class Varien_Data_Collection it will return array of this &quot;item&quot;
				*/
                $this-&gt;addItem($item);
            }

        }

        $this-&gt;_setIsLoaded();
        $this-&gt;_afterLoad();
        return $this;
    }

    /**
     * Get all data array for collection
     * @class Varien_Data_Collection_Db
     * @return array
     */
    public function getData()
    {
        if ($this-&gt;_data === null) {
            $this-&gt;_renderFilters()
                 -&gt;_renderOrders()
                 -&gt;_renderLimit();

			// Fetching all the row with the Select query set
            $this-&gt;_data = $this-&gt;_fetchAll($this-&gt;_select);
            $this-&gt;_afterLoadData();
        }
        return $this-&gt;_data;
    }
</pre>
<p>You can go through the inline comments I&#8217;ve added. This is it, I&#8217;ve finally worked out the explanation of structure &amp; creation of Magento&#8217;s Collection and its iterative behavior. I&#8217;ve tried to show pictorially (below) what I have just described. Confused! Plz comment and of course please do comment if I am wrong, because there are &#8220;times&#8221; when you try to understand things even though they actually aren&#8217;t just like you think. I&#8217;d like to quote <strong>Paulo </strong> :<strong><em>&#8220;I see the world in terms of what I would like to see happen, not what actually does&#8221;</em></strong>!</p>
<p><img class="alignnone size-full wp-image-249" title="hierarchy" src="http://subesh.com.np/wp-content/uploads/2010/05/hierarchy.jpg" alt="hierarchy" width="505" height="604" /></p>
]]></content:encoded>
			<wfw:commentRss>http://subesh.com.np/2010/05/analysis-usage-collections-magento/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Getting Customer&#039;s Info Using Single Query Including Billing and Shipping Addresses</title>
		<link>http://subesh.com.np/2010/01/customers-info-single-query-including-billing-shipping-addresses/</link>
		<comments>http://subesh.com.np/2010/01/customers-info-single-query-including-billing-shipping-addresses/#comments</comments>
		<pubDate>Mon, 18 Jan 2010 08:49:45 +0000</pubDate>
		<dc:creator>Subesh Pokhrel</dc:creator>
				<category><![CDATA[Magento]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[Query]]></category>
		<category><![CDATA[String]]></category>
		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://subesh.com.np/?p=184</guid>
		<description><![CDATA[Query in Magento can be quite troublesome, if you are a starter..or non-starter. So I&#8217;ve tried to share some of the difficult queries using collection in Magento, so that it will be helpful to my blog readers and also a place where I can later refer to. Here is one of them, may not be [...]]]></description>
			<content:encoded><![CDATA[<p>Query in Magento can be quite troublesome, if you are a starter..or non-starter. So I&#8217;ve tried to share some of the difficult queries using collection in Magento, so that it will be helpful to my blog readers and also a place where I can later refer to. Here is one of them, may not be dificult to all, but for me I had a very bad time initially, when I first started on Magento about a year ago. I had always thought to post on my blog, but when one of my collegue asked me about this I remembered and here&#8217;s the query.</p>
<pre class="brush: php; title: ; notranslate">
$collection = Mage::getResourceModel('customer/customer_collection')
				-&gt;addNameToSelect()
				-&gt;addAttributeToSelect('email')
				-&gt;addAttributeToSelect('created_at')
				-&gt;addAttributeToSelect('group_id')
				-&gt;joinAttribute('billing_street', 'customer_address/street', 'default_billing', null, 'left')
				-&gt;joinAttribute('billing_postcode', 'customer_address/postcode', 'default_billing', null, 'left')
				-&gt;joinAttribute('billing_city', 'customer_address/city', 'default_billing', null, 'left')
				-&gt;joinAttribute('billing_telephone', 'customer_address/telephone', 'default_billing', null, 'left')
				-&gt;joinAttribute('billing_fax', 'customer_address/fax', 'default_billing', null, 'left')
				-&gt;joinAttribute('billing_region', 'customer_address/region', 'default_billing', null, 'left')
				-&gt;joinAttribute('billing_country_code', 'customer_address/country_id', 'default_billing', null, 'left')

				-&gt;joinAttribute('shipping_street', 'customer_address/street', 'default_shipping', null, 'left')
				-&gt;joinAttribute('shipping_postcode', 'customer_address/postcode', 'default_shipping', null, 'left')
				-&gt;joinAttribute('shipping_city', 'customer_address/city', 'default_shipping', null, 'left')
				-&gt;joinAttribute('shipping_telephone', 'customer_address/telephone', 'default_shipping', null, 'left')
				-&gt;joinAttribute('shipping_fax', 'customer_address/fax', 'default_shipping', null, 'left')
				-&gt;joinAttribute('shipping_region', 'customer_address/region', 'default_shipping', null, 'left')
				-&gt;joinAttribute('shipping_country_code', 'customer_address/country_id', 'default_shipping', null, 'left')
				-&gt;joinAttribute('taxvat', 'customer/taxvat', 'entity_id', null, 'left');
</pre>
<p>Hope this helps somebody!</p>
]]></content:encoded>
			<wfw:commentRss>http://subesh.com.np/2010/01/customers-info-single-query-including-billing-shipping-addresses/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using Custom Query in Magento</title>
		<link>http://subesh.com.np/2009/12/using-custom-query-in-magento/</link>
		<comments>http://subesh.com.np/2009/12/using-custom-query-in-magento/#comments</comments>
		<pubDate>Tue, 08 Dec 2009 08:33:01 +0000</pubDate>
		<dc:creator>Subesh Pokhrel</dc:creator>
				<category><![CDATA[Magento]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Query]]></category>
		<category><![CDATA[String]]></category>

		<guid isPermaLink="false">http://subesh.com.np/?p=133</guid>
		<description><![CDATA[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 &#38; Collection in Magento). But [...]]]></description>
			<content:encoded><![CDATA[<p>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 &amp; Collection in Magento). But by Magento&#8217;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.</p>
<p>The idea is simply to get the core connection object and use its functions to run your query.</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
// For Read

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

print_r($row); // As Array

// For Write

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

// now $write is an instance of Zend_Db_Adapter_Abstract
$write-&gt;query(&quot;insert into tablename values ('aaa','bbb','ccc')&quot;);

?&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://subesh.com.np/2009/12/using-custom-query-in-magento/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>How to get Query as a String in Magento?</title>
		<link>http://subesh.com.np/2009/11/how-to-get-query-as-a-string-in-magento/</link>
		<comments>http://subesh.com.np/2009/11/how-to-get-query-as-a-string-in-magento/#comments</comments>
		<pubDate>Mon, 16 Nov 2009 13:48:33 +0000</pubDate>
		<dc:creator>Subesh Pokhrel</dc:creator>
				<category><![CDATA[Magento]]></category>
		<category><![CDATA[Query]]></category>
		<category><![CDATA[String]]></category>

		<guid isPermaLink="false">http://subesh.com.np/?p=81</guid>
		<description><![CDATA[Magento as you might know or not! has really a very PIA (Pain in the A**) type of methods to create SQL, execute and fetch! There are two ways of getting SQL from the collection of Magento. Here are the two ways. 1. Only Echoing Query String. For just echoing the query string you must [...]]]></description>
			<content:encoded><![CDATA[<p>Magento as you might know or not! has really a very PIA (Pain in the A**) type of methods to create SQL, execute and fetch! There are two ways of getting SQL from the collection of Magento. Here are the two ways.</p>
<p><strong>1. Only Echoing Query String.</strong><br />
For just echoing the query string you must call printlogquery(), method the the collection. Like.</p>
<pre class="brush: php; title: ; notranslate">
/** If $collection is your collection**/
$collection-&gt;printlogquery(true);
/** Don't forget to write true in param**/
</pre>
<p>But by this method you cannot assign the query you get echoed to some variable. To get the query string here is what you do.</p>
<p><strong>2. Getting the query String</strong></p>
<pre class="brush: php; title: ; notranslate">
$query=$collection-&gt;getSelectSql(true);
echo $query;
</pre>
<p>You can then use this $query to concat with more query, in some cases you desperately need this.</p>
<p>Stay Tuned!</p>
]]></content:encoded>
			<wfw:commentRss>http://subesh.com.np/2009/11/how-to-get-query-as-a-string-in-magento/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

