Alternating table row color

Team,

I have searched the internet and found many samples of alternating row color when retrieving from MySQL. I have attempted many times to try these and have failed. I would appreciate someone taking the time to review my posted script, and showing me where I need to put what. I’d like to learn, but I’m getting frustrated here. Thank you in advance for your help.
[php] <?php

$table = ‘POs’;

if (!mysql_select_db($database))
die(“Can’t select database”);

// sending query
$result = mysql_query(“SELECT * FROM {$table}”);
if (!$result) {
die(“Query to show fields from table failed”);
}

$fields_num = mysql_num_fields($result);
$color = 0;
echo “

”;
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo “”;
}
echo “\n”;
// printing table rows
while($row = mysql_fetch_row($result))
{
echo “”;
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
    echo "<td>$cell</td>";

echo "</tr>\n";

}

mysql_free_result($result);
?>[/php]

{$field->name}

I didn’t test it, but it should work.

[php] <?php

$table = 'POs';

$i = 0;

if (!mysql_select_db($database))
die(“Can’t select database”);

// sending query
$result = mysql_query(“SELECT * FROM {$table}”);
if (!$result) {
die(“Query to show fields from table failed”);
}

$fields_num = mysql_num_fields($result);

$bg_shade = ($i++ % 2 == 0) ? ‘#EfEfEf’ : ‘#dddddd’;
echo “

”;

// printing table headers
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo “

”;
}
echo “\n”;
// printing table rows
while($row = mysql_fetch_row($result))
{

$bg_shade = ($i++ % 2 == 0) ? ‘#EfEfEf’ : ‘#dddddd’;
echo “

”;
 // $row is array... foreach( .. ) puts every element
 // of $row to $cell variable
 foreach($row as $cell)
     echo "<td>$cell</td>";

 echo "</tr>\n";

}

mysql_free_result($result);
?>[/php]

{$field->name}

If you aren’t conserned about old IE versions I’d recommend doing this in css. Look into nth-child :slight_smile:

a slight variation to topcoders is what i do:
[php]$bg_color = ($i++ % 2 == 0) ? ‘bgcolor’ : ‘bgcolor_alt’;
echo “

”;[/php]

This way i can change the colours easily in the css without having to dig into the php code. (and if you have 50+ pages, saves a whole lot of time too!)

Red :wink:

That’s an excellent suggestion Redscouse.

:smiley: ;D

Sponsor our Newsletter | Privacy Policy | Terms of Service