0

I have this php query

$sql = "SELECT * FROM db";
$query = mysql_query($sql);
while($row = mysql_fetch_assoc($query))

{

   echo "<ul>";

   echo "<li>{$row['title']}</li>";

   echo "</ul>";

}

and my xhtml code is:

<ul>
<li class="pdn5">one</li>
<li class="pdn5">two</li>
<li class="no-pdn">three</li>
</ul>

In this case, how can write the php loop? Thanks in advance

2 Answers 2

3

Assuming you want the last row to be the only one with "no-pdn", then you could use this:

$sql = "SELECT * FROM db";
$query = mysql_query($sql);
$numRows = mysql_num_rows($query);
$i = 1;
while($row = mysql_fetch_assoc($query))
{    
   echo "<ul>";    
   echo '<li class="'.($i < $numRows ? 'pdn5' : 'no-pdn').'">'
         .$row['title']."</li>";
   echo "</ul>";
   i++;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Modify your code like this:

$sql = "SELECT * FROM db";
$query = mysql_query($sql);
   echo "<ul>";
while($row = mysql_fetch_assoc($query))

{
   echo "<li class='some_class'>{$row['title']}</li>";
}
   echo "</ul>";

Update for class name of li element:

If your want to add specific classes for each of the list element, you can, for example, store this class name in DB and retrieve it with your title. Or it's also possible to make class name, based on the $row['title'] value. For example:

echo "<li class='li_".$row['title']."'>{$row['title']}</li>";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.