可能重复:
How to set alternate row color for an iterated table in php?
Using CSS :even and :odd pseudo-classes with list items
我有一个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应用于每个第二行。我怎么能这样做?
答案 0 :(得分:3)
使用:
$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++
}
答案 1 :(得分: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";
}