DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Kenneth has posted 3 posts at DZone. View Full User Profile

Alternating Table Colors For Rows And Columns.

08.10.2007
| 6534 views |
  • submit to reddit
        This code will provide 8 colors for cells and set of 8 lighter colors for alternating rows.
<?php
$sql  = 'SELECT * FROM `table` WHERE `column` = \'something\'';
$qry = mysql_query($sql) or die(mysql_error());

// Cell colors for odd rows
$c1  = array('#00CCCC', '#33CC00', '#CC0000', '#CCCC00', '#0000CC', '#FF6600', '#CC00CC', '#00CC99');

// Cell Colors for even rows
$c2  = array('#66FFFF', '#66FF00', '#FF3300', '#FFFF33', '#0033FF', '#FF9933', '#FF33CC', '#00FF99');

// Row Counter
$cnt  = 0;

$ret = '<table>';
while($row = mysql_fetch_assoc($qry))
{
  // Cell counter
  $cnt2 = 0;
  $ret  .= '<tr>';
  foreach($row as $key=>$val)
   {
    $ret .= '<td bgcolor="';

    if($cnt % 2)
      {
        $ret .= $c1[$cnt2];
      }
    else
      {
        $ret .= $c2[$cnt2];
      }

    $ret .= '">'.$val.'</td>';
    ++$cnt2;
   }
  ++$cnt;
  $ret .= '</tr>'."\n";
}
$ret .= '</table>';

echo $ret;
?> 
    

Comments

Kenneth Mccall replied on Fri, 2007/08/10 - 11:56am

Just before the loop - put in a tr and some tds

Snippets Manager replied on Thu, 2008/06/12 - 8:45pm

Can someone assist me in rewriting the above column and row coloring code to include field names at top of table. I am stumped!!