enjoylife
enjoylife

Reputation: 5479

how to add the class="last" to the last line in the loop

the above is form the database, which used the LIMIT 0, 10.($result)

         while ($row = mysql_fetch_object($result)){
                   echo '<li>'.$row->title.'</li>';
          }

now i want to add the class="last" to the 10 line. this is my ways. but it can't work. how to correct it or using another way to get that?

  while ($row = mysql_fetch_object($result)){
      $num=0;
      if($num==9){
                   echo '<li class="last">'.$row->title'</li>';
          }else{ echo '<li>'.$row->title.'</li>';}
       $num++;
     }

Upvotes: 0

Views: 293

Answers (3)

S L
S L

Reputation: 14318

Define $num=0; outside the while loop.

You are defining $num=0; inside while so ++$num; has no meaning at all. It will set to 0.

Well, the logic is like this.

$j = 0; /* $j is outside the loop, so it does not repeat. */    

for($i=0; $i<=10; $i++)
{   
    $k = 0;     
    /*      
    Its because the loop repeats,
    And $k is set to 0 at the above step.        
    */      
    echo "j: ".($j++)." k:".($k++)."<br/>"; 
}

Upvotes: 4

Gowri
Gowri

Reputation: 16835

using another way

using css

li:last-child{
/*add properties of that class(last) here*/
}

Upvotes: 1

Pascal MARTIN
Pascal MARTIN

Reputation: 400932

In order to know if you are on the last line of your resultset, you have to know how many lines there are in that resultset (as, of course, you could have less than 10 rows) ; two possible solutions :

  • Use a select count() query, with the same where clause as your select query that gets you the data, to find out if you have less than 10 rows, or more than 10 rows.
  • Or fetch the whole resultset to an array first, and, only after that, display it -- using count() to know how many rows there are in that array.

Another possibility could be to use the [**`mysql_num_rows()`**][2] function, to get the total number of rows -- which will allow you to know if you're on the last one *(quoting)* :

Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set.


In any case, you'll then have to keep track of the number of lines you've displayed -- to know if you are on the last one.

Note : this means using some counter variable as you did ; except you'll want to initialize it to 0 outside of the loop !
Else, reseting to 0 each time you loop, you'll never know on which line you are !

Upvotes: 1

Related Questions