Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

In my code, 'product' table is returning every product details in the table.

Now I want to get specific product details of 0 to 5th product. How can I change this while loop to a for loop?

Code:

public function getProducts(){
    $query = "SELECT * FROM shop_product";
    $resultSet = Array();
    $result = mysql_query($query) or die (mysql_error());

    while($fetchResult = mysql_fetch_array($result,MYSQL_ASSOC)){
        $resultSet[] = $fetchResult;
    }
    mysql_free_result($result);

    return $resultSet;
}
share|improve this question
2  
Your existing query returns every column for every row in your table. If you just want five rows this is incredibly wasteful. Change your query to add a limit: SELECT * FROM shop_product LIMIT 0,5 –  Mike W May 2 at 4:03

2 Answers 2

up vote 1 down vote accepted

You could simply change your query instead to return top five rows.

SELECT * FROM shop_product LIMIT 0,5

(or)

If you don't prefer the above solution, you could use array_slice() to get a portion of the array..

while($fetchResult = mysql_fetch_array($result,MYSQL_ASSOC)){
        $resultSet[] = $fetchResult;
    }
    $fiverowsarray = array_slice($resultSet, 0 , 5); //<--- You can add like this..
share|improve this answer
1  
It worked.Thanks for the answer. –  udi May 2 at 5:08
    
@udi, Your welcome happy coding ! –  Shankar Damodaran May 2 at 5:08

Try with LIMIT and Where conditions

public function getProducts(){
    $query = "SELECT * FROM shop_product LIMIT 0,5";
    $resultSet = Array();
    $result = mysql_query($query) or die (mysql_error());

    while($fetchResult = mysql_fetch_array($result,MYSQL_ASSOC)){
        $resultSet[] = $fetchResult;
    }
    mysql_free_result($result);

    return $resultSet;
}
share|improve this answer
1  
$product_id isn't set anywhere so this will fail straight way. In any case, why limit to five when the where clause will only return one product anyway? This doesn't help the OP at all. –  Mike W May 2 at 4:20
    
@Mike W User says I want to get specific product details of 0 to 5th product –  Sadikhasan May 2 at 4:39
    
Yes he does. Your query, if it worked, would return just one product, not five. –  Mike W May 2 at 4:44
    
Sorry product_id is not required here –  Sadikhasan May 2 at 4:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.