PHP:每隔一行应用CSS


PHP: apply CSS to every second row

可能重复:
如何在php中为迭代表设置备用行颜色
使用带有列表项的CSS:even和:odd伪类

我有一个html表,其中填充了来自mysql表的数据。我使用以下代码:

$result = mysql_query("SELECT * FROM {$table}");
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
echo "<h1>Table: {$table}</h1>";
echo "<tr>";
echo "</tr>'n";
while($row = mysql_fetch_row($result))
{
echo "<tr>";
foreach($row as $cell)
    echo "<td>$cell</td>";
echo "</tr>'n";
}
mysql_free_result($result);

注意:我通常使用PDO语句,但在本例中,我使用mysql。

代码正确地生成了表。问题是:我想用下面的class=table_higlight将CSS应用于每一行。我该怎么做?

使用:

$i = 0;
while($row = mysql_fetch_row($result)) {
  if ($i % 2 == 0 )
    echo '<tr class="even">';
  else
    echo '<tr class="odd">';
  foreach($row as $cell)
    echo "<td>$cell</td>";
  echo "</tr>'n";
  $i++
}
while($row = mysql_fetch_row($result))
{
echo "<tr".(++$ctr%2 == 0 ? ' class="table_highlight"' : '').">";
foreach($row as $cell)
    echo "<td>$cell</td>";
echo "</tr>'n";
}