Jump to content

Simple Alternating Rows Gone Wrong...


SelfObscurity

Recommended Posts

Evening,

 

It's been over a year since I've dealt with PHP...I actually stepped a way for a while.  I'm working back into re-teaching, since I was learning when I was actively coding.  I found a simple way to call for alternating rows via PHP based on the row #.  The snippet of code works, but I don't know enough about the mathematics end of the coding to stop this duplicating.  See code below.

 

<?php
                   	$result = mysql_query("SELECT * 
				FROM navigation");

				while($row = mysql_fetch_array($result))
				{

				for($i=0; $i<2; $i++)
				{
    				$class = 'row' . ($i % 2);

    				?>

 

And then the code that calls the row

<td valign="middle" class="<?php echo "$class" ?>"><span class="red2">»</span> <a href="<?php echo $row['url'] ?>"><?php echo $row['text'] ?></a></td>
            </tr>
		<?php 
		}
		} ?>

 

The code works, but it is doubling each row.  Please help?  I assume it is the snippet:

 

for($i=0; $i<2; $i++)

...but don't know enough and can't reallty find any resources to assist.

 

Jon

Link to comment
https://forums.phpfreaks.com/topic/183194-simple-alternating-rows-gone-wrong/
Share on other sites

Thanks for the post thorpe.  I remove the loop and i get a basic syntax error...so maybe I am unsure how this is supposed to look.  I've never dont this particular thing before, thus the use of a tutorial snippet.  How should this look?

Its quite simple.

 

<?php
$i=0;
while ($row = mysql_fetch_array($result)) {
  $class = ($i % 2) ? 'even' : 'odd';
  ?>
  <td valign="middle" class="<?php echo $class ?>"><span class="red2">»</span> <a href="<?php echo $row['url'] ?>"><?php echo $row['text'] ?></a></td>
  <?php
  $i++;
}
?>

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.