search
top

Limit results collection in Magento

Many times need arises to limit collection for say pagination or for any customization.

I am listing here an example which shows how to limit the collection.

I have used the Product Model below.

<?php
$limit = 5;
$starting_from = 2;
$product_collection = Mage::getModel('catalog/product')->getCollection()->setOrder('name', 'asc'); //getting the product collection, results are ordered by product name
$product_collection->getSelect()->limit($limit,$starting_from);	//where	$limit will be the number of results we want, $starting_from will be the index of the result set to be considered as starting point (note 0 is the index of first row)
//this will ouptput 5 records starting from 3rd record
foreach($product_collection as $_product)
{
	echo $_product->getName().'<br/>'; 
}
?>

Suppose the first 10 products (ordered by name) are

A
B
C
D
E
F
G
H
I
J

The above foreach will output

C
D
E
F
G

10 Responses to “Limit results collection in Magento”

  1. Louis says:

    Thank you very much! it is really useful.
    I like getSelect in magento to query data base!

  2. Armin says:

    You can also use setPageSize() for setting page limit in product collection..

  3. vm says:

    Really this post was useful. Thank you!1

  4. sunil says:

    i want to limit related product, up-sell product, featured product limit.
    i

  5. prasad says:

    Hi, can you please reply me how to put limit for custome table collection.

  6. عقار says:

    Thank you
    Very beautiful

Leave a Reply

top