Question

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;
}
Was it helpful?

Solution

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..

OTHER TIPS

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top