如何使用php添加不同的CSS到最后的mysql查询结果

I'm retrieving 4 latest items from the database and show them in a list. My question is that how can I add a different HTML class to the last item?! for example,

<ul>
    <li class="list">number 1</li>
    <li class="list">number 2</li>
    <li class="list">number 3</li>
    <li class="list last-child">number 4</li> 
</ul>

how can I add last-child to the last item using php?

Instead of assigning a class using PHP, use :last-child pseudo instead

ul.class_name li:last-child { /* This will target last li in the ul */
   /* Styles */
}

Demo

Better assign a class to your ul element to distinguish with other ul elements in the same document.


If you want to literally add the class to the DOM for some reason than you can use a counter variable with mysqli_num_rows (Here I assume you are atleast using mysqli_()).

$counter = 0;
$total_rows = mysqli_num_rows($query);

while($throw_results = mysqli_fetch_array($query)) {
   $counter++; /* Increment the counter by 1 */
   if($total_rows == $counter) {
      /* Add class if total rows = counter value */
   }
}

Try this

<div>
  <span>John,</span>
  <span>Karl,</span>
  <span>Brandon,</span>
  <span>Sam</span>
</div>

<script>
$( "div span:last-child" )
  .css({ color:"red", fontSize:"80%" })
  .hover(function() {
    $( this ).addClass( "solast" );
  }, function() {
    $( this ).removeClass( "solast" );
  });
</script>
$i= 0;
$total_rows = mysql_num_rows($rs);


 while($result=mysql_fetch_array($rs))
    {
        echo ($i == $total_rows ) ? '<li class="list">number 1</li>
<li class="list">number 2</li>
<li class="list">number 3</li>
<li class="list last-child">number 4</li> ' :'<li class="list">number 1</li>
<li class="list">number 2</li>
<li class="list">number 3</li>
<li class="list">number 4</li> ';
        $i++;
    }