如何使PHP html表的行之间颜色不匹配


How to make PHP html table have color mismatch between rows?

我在学习PHP的同时编写代码。在w3schools上的一个例子中,它展示了使用PHP和msql在html表上显示数据库结果。我的问题是,我现在有太多的行,我无法使它们的行之间的颜色不匹配。我试过在<td之后添加样式跨度和字体颜色,但没有成功。如果我这样做,整个PHP就不起作用了。

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "</tr>";
  }
echo "</table>";
mysql_close($con);
?>

上面代码的输出将是:

Firstname   Lastname
Glenn   Quagmire
Peter   Griffin

http://www.w3schools.com/php/php_mysql_select.asp

不完全确定颜色不匹配是什么意思。假设你的意思是交替的行颜色,我会做以下操作:

$odd = false;
while (...)
{
    echo '<tr class="'.($odd ? "odd" : "even").'">';
    ...
    echo "</tr>";
    $odd = !$odd;
}

现在,tr元素交替地属于oddeven类,并且可以在CSS中为其中一个元素指定一些额外的背景颜色,例如:

tr.odd { background-color: rgba(0, 0, 0, 0.05); }

替换此:

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "</tr>";
  }

这个:

$i = 0;
while($row = mysql_fetch_array($result))
  {
  echo "<tr ". ($i % 2 == 0 ? 'style="background-color:grey;"' : '' .">";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "</tr>";
  $i++;
  }

每隔一行将显示灰色。

也许您可以将这种方法与jquery 一起使用

<script src="text/javascript">
    $('#table tbody tr:odd').addClass('odd');
    $('#table tbody tr:even').addClass('even');
</script>

然后添加样式

.odd { background-color: #color }
.even { background-color: #color }
$class = "even";    
while($row = mysql_fetch_array($result))
{
  if($class == "even")
  {
    echo "<tr class='$class'>";
    $class = "odd";
  }
  else
  {
    echo "<tr class='$class'>";
    $class = "even";
  }
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "</tr>";
}

CSS

tr.even
{
    background-color:blue;//Pick your own color
}
tr.odd
{
    background-color:green;
}

这是一个颜色名称列表。如果您想要更详细的颜色选择,请单击此处。

使用

  $flag = 0;
  while($row = mysql_fetch_array($result))
  {
  if ($flag%2 == 1)
  echo "<tr bgcolor=#123345>";
  else
  echo echo "<tr bgcolor=#643235>";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "</tr>";
  $flag = $flag +1;
  }