1

可能重复:
如何在 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。

代码正确生成表。问题是:我想对每隔一行应用一个 CSS,如下class=table_higlight. 我怎样才能做到这一点?

4

2 回答 2

4

利用:

$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++
}
于 2012-09-03T17:06:50.323 回答
1
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";
}
于 2012-09-03T17:01:37.523 回答