PDA

View Full Version : Listing Top 10 using $i



e1seix
11-16-2007, 10:44 PM
a simple question i know but i'm having trouble implementing it with the following code:


while($row = mysql_fetch_array( $fetch )) {

// Print out the contents of each row into a table
echo "<tr>";
echo "<td style='border-bottom: 1px solid #000000;text-align:center'>";

echo "<span class='lip2'>";
echo '* <a href="'.$_HTTPS['PHP_SELF'].'show.php?sku='.$row['sku'].'&productDetail='.$row['title'].'" style="color:#000000">';
echo $row['size']." ";
echo $row['title']." ";
echo $row['type'];
echo "</a>";
echo "</span>";
echo "</td>";
echo "</tr>";

}

I need to replace the "*" with conscentric numbers listing 1 to 10 as the 10 results are listed. i know it's a for i loop but i can't seem to get it right. any help?

many thanks,

djr33
11-16-2007, 11:30 PM
A for loop is a complex while loop.

while (condition) { operations }
That means "while [condition] evaluates as true, do the operations." Also, the condition statement itself is also done, and its return value (true or false) determines if the loop continues.

A for loop is just a bit more than that:
for (start_do_this; condition; each_do_this) { operations }
Means "first, to the start_do_this operation. Then, while [condition] evaluates as true, do the operations, AND at the beginning of every iteration, do the each_do_this operation"

for ($i=1; $i<10; $i++) { }
echo $i;
That would echo 10 at the end.
Start $i as one, then continue through the loop (which does nothing inside it-- I'm not actually positive that's valid-- might need something in there, but just an example anyway). Before each loop, add one to $i. Then, it'll stop continuing once $i reaches 10.


So, here's what you could do:
(Remember, arrays start at 0, not 1-- so I'm using 0 and 9, not 1 and 10)
for ($i=0; ($row = mysql_fetch_assoc($results) && $i<9); $i++) {
...
}

However, the better way in this might be to use limits with the query itself.
[query]... LIMIT 1, 10

See more info on this process here, and the whole tutorial is helpful too.
http://www.php-mysql-tutorial.com/php-mysql-paging.php