Jump to content

Alternating Style While Fetching Database Info


MrXander

Recommended Posts

Hi guys.

 

I'm making a comment system for my website but I'm a bit stuck.

 

I need to be able to alternate the style of every other comment with the stylesheet I have set, but how do I do this while fetching results from my database? I need to change the <li class="comment_even"> to <li class="comment_odd"> every other comment.

 

<?php
 $sql2 = mysql_query("SELECT * FROM `comments` WHERE `relatingto`='".$_GET['id']."' AND `hidden`='No' AND `deletedbyadmin`='No'");
 while($dat2 = mysql_fetch_array($sql)){
 ?>
 <li class="comment_even">
	    <div class="author"><img class="avatar" src="images/avatar.gif" width="32" height="32" alt="" /><span class="name"><a href="#"><?php echo $dat2['poster']; ?></a></span> <span class="wrote">wrote:</span></div>
	    <div class="submitdate"><a href="#"><?php echo $dat2['time']; ?></a></div>
	    <p><?php echo $dat['comment']; ?></p>
	  </li>
   <?php
   }
   ?>

You just need to implement some logic like this. If you run it, you should be able to figure it out easily enough.

 

<?php
$i = 0;
while( $i < 10 ) {
   $class = $i %2 == 0 ? 'even' : 'odd';
   echo "$class<br>";
   $i++;
}

Try this:

<?php
$sql2 = mysql_query("SELECT * FROM `comments` WHERE `relatingto`='".$_GET['id']."' AND `hidden`='No' AND `deletedbyadmin`='No'");
while($dat2 = mysql_fetch_array($sql)){
$comment = ($comment == 'comment_odd') ? 'comment_even' : 'comment_odd'; //if $comment is 'comment_odd, change to comment_even, else change to comment_odd. Numbers start off odd right? 
?>
<li class="<?php echo $comment; ?>">
<div class="author"><img class="avatar" src="images/avatar.gif" width="32" height="32" alt="" /><span class="name"><a href="#"><?php echo $dat2['poster']; ?></a></span> <span class="wrote">wrote:</span></div>
<div class="submitdate"><a href="#"><?php echo $dat2['time']; ?></a></div>
<p><?php echo $dat['comment']; ?></p>
</li>
<?php
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.