Ben
Ben

Reputation: 65

Change class for last two rows in a while loop

I have a while loop that displays result from a MySQL query. I know how to change the output for the last row or an odd row but how can I change the output for the last two results?

For example I have a list of results in a 2x2 matrix with border-bottom: 1px on each result but I would like to display the bottom two without the border?

Upvotes: 3

Views: 370

Answers (3)

Michael Rose
Michael Rose

Reputation: 7820

Yeah just do it like this:

$result = //execute your query
$num_rows = mysql_num_rows($result;
$num_rows_different = 2;

$loop_counter = 0;
while ($loop_counter < $num_rows) {
   if ($loop_counter < $num_rows - $num_rows_different) {
      // with border
   } else {
      // no border
   }
   $loop_counter++;
}

I wouldn't use the CSS3 method due to its poor support...

Upvotes: 0

Aaron W.
Aaron W.

Reputation: 9299

I like the CSS way, but you'll need to know the total number of items you're listing. Then you can use a simple condition to check for that.

$total_items = [count of items];
$cnt = 0;
while($fetch as $row) {
    ...
    if(++$cnt > ($total_items - 2)) {
        // list with no border
    } else {
        // list with border
    }
}

Upvotes: 0

jeroen
jeroen

Reputation: 91734

If you can use css3, it´s easy (I´ll use a list for the example):

li:nth-last-child(-n+2)

selects the last two li's.

If you want to do it in php, you can count the number of results, add a counter in your loop and add a class to the last two items.

Upvotes: 4

Related Questions