Page 1 of 1

Alternating color in table output background

Posted: Fri Mar 04, 2011 9:35 am
by teknospr
Good day:

I'm trying to get the following output to alternate colors of background (white and gray or other colors). Any help will be appreciated.

(This is the entire script so far.)


<html>
<body>
<?php
$connection = mysql_connect("localhost",
"username",
"password");

mysql_select_db("articles", $connection);
$query="SELECT * FROM articles WHERE id=1";
$result=mysql_query($query);

$num=mysql_numrows($result);

mysql_close();
?>
<table border="1" cellspacing="2" cellpadding="2">
<tr>
<th><font face="Arial, Helvetica, sans-serif">Article</font></th>
<th><font face="Arial, Helvetica, sans-serif">Year</font></th>
<th><font face="Arial, Helvetica, sans-serif">Description</font></th>
<th><font face="Arial, Helvetica, sans-serif">Location</font></th>

</tr>

<?php
$i=0;
while ($i < $num) {

$f1=mysql_result($result,$i,"article");
$f2=mysql_result($result,$i,"year");
$f3=mysql_result($result,$i,"description");
$f4=mysql_result($result,$i,"location");
$f5=mysql_result($result,$i,"link")
?>

<tr>
<td><font face="Arial, Helvetica, sans-serif"><?php echo $f1; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><?php echo $f2; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><?php echo $f3; ?></font></td>
<td ><font face="Arial, Helvetica, sans-serif"><?php echo "<a href=\"$f5\" target=\"_blank\">$f4</a>"; ?></font></td>
</tr>
<tr>
</tr>

<?php
$i++;
}
?>
</body>
</html>

Re: Alternating color in table output background

Posted: Fri Mar 04, 2011 9:59 am
by pickle
OK, a number of things:
  1. Your loop can be improved to:

    Code: Select all

    while($row = mysql_fetch_assoc($result))
    {
      $f1 = $row['article'];
      $f2 = $row['year'];
      ..etc
    }
    This way you don't need to fart around with $i
  2. Use a stylesheet & CSS. The "font" tag is super deprecated - you should be declaring the font in CSS. While you're there, declare two classes "odd" and "even".
  3. Set a variable outside your loop, then toggle it inside your loop to determine how the table row should look:

    Code: Select all

    $row_class = 'even';
    while()
    {
      $row_class = ($row_class == 'even') ? 'odd' : 'even';
    ?>
    <tr class = "<?php echo $row_class; ?>">
    ...