我想要do样式表,但它没有;我不能用PHP


I want do style tables, but it doesn't work in PHP

我想创建一个网站,它显示数据库中的大量记录。为了让它对读者更友好,我想使用一种样式。一条记录是白色背景,下一条是蓝色,下一个是hhite。

所以我尝试了这个:

<?php while ($info = mysql_fetch_array($data)){
PRINT "<tr>";
PRINT "<td>"  .$info['articlenr']. "</td>";
PRINT "<td>"  .$info['stock']. "</td>";
PRINT "</tr>";
PRINT "<tr>";
PRINT "<td bgcolor=#0066FF>"  .$info['articlenr']. "</td>";
PRINT "<td bgcolor=#0066FF>"  .$info['stock']. "</td>";
PRINT "</tr>";
}
?>

这适用于视图,但问题是,蓝色记录与白色记录相同,而不是下一个,它只是将记录加倍,使其变成另一种颜色。

我该怎么做?

使用:nth-of-type(even)获得颜色的偶数/奇数组合。

下面是一个演示示例:

html:

<table>
<tr><td>item1</td>
</tr>
<tr><td>item2</td>
</tr>
<tr><td>item3</td>
</tr>
<tr><td>item4</td>
</tr>
</table>

css:

tr:nth-of-type(even) { background-color: #0066FF; }

演示

如果你想在PHP中做到这一点,你可以这样做:

<?php 
$iter = 0;
$color1 = 'red'; //can se hex code too, like #0066FF;
$color2 = 'blue';
while ($info = mysql_fetch_array($data))
{
    echo '<tr style="background-color:'.( ($iter%2==0) ? $color1 : $color2).';">';
    // rest of the printing stuff
    $iter++;
}
?>

报表

($iter%2==0) ? $color1 : $color2

这样做:它询问迭代器(或行号)是否为偶数。如果是,则需要color1。如果不是(行不均匀),则使用第二种颜色。

PHP Smarty很适合做这类事情(迭代颜色和样式),但对初学者来说可能很困难。

请浏览以下链接:

https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started

http://css-tricks.com/complete-guide-table-element/

在.php文件中包含CSS

我能为您的代码提供一些建议吗?您的方法将PHP和HTML混合在一起,使您的开发环境很难解析HTML,而且您可以用更少的按键实现同样的目的!请考虑这种方法:

<?php while ($info = mysql_fetch_array($data)): ?>
    <tr>
        <td><?php echo $info['articlenr'] ?></td>
        <td><?php echo $info['stock'] ?></td>
    </tr>
<?php endwhile ?>

我所做的改变:

  • 删除了重复的行
  • 以HTML模式呈现所有内容,并仅为PHP代码打开PHP标记
  • 将循环切换为冒号形式,这在模板中通常被认为更清晰。但是,在大块代码(例如类)中,请继续使用大括号方法
  • 小写编写的PHP关键字
  • 使用echo而不是print

将此与Joke_Sense10的答案结合起来,即可获得完整的解决方案。