0

我想使用 php 从数据库中以表格形式输出数据。& 在表格中使用其他颜色

但它不显示替代颜色,浏览器在 php 代码开始之前制作 div 标签,因此颜色不显示。

部分代码:

$result = mysqli_query($con, "SELECT * FROM form1 ORDER by id   ");

    echo "<table border=1>
        <tr>
        <th>id</th>
        <th>Name</th>
        <th>userName</th>
        <th>e-Mail id</th>";

    while ($row = mysqli_fetch_array($result)) {
        if ($row['id'] % 2 == 1) {

            echo '<div class = "odd">';
            echo "<tr>";
            echo "<td>" . $row['id'] . "</td>";
            echo "<td>" . $row['name'] . "</td>";
            echo "<td>" . $row['username'] . "</td>";
            echo "<td>" . $row['mail'] . "</td>";
            echo "</tr>";
            echo '</div>';
        } else {
            echo '<div class = "even">';
            echo "<tr>";
            echo "<td>" . $row['id'] . "</td>";
            echo "<td>" . $row['name'] . "</td>";
            echo "<td>" . $row['username'] . "</td>";
            echo "<td>" . $row['mail'] . "</td>";
            echo "</tr>";
            echo '</div>';
        }
    }

    echo "</table>";
4

3 回答 3

3

只需将课程设置为 TR

$result = mysqli_query($con, "SELECT * FROM form1 ORDER by id   ");

echo "<table border=1>
    <tr>
    <th>id</th>
    <th>Name</th>
    <th>userName</th>
    <th>e-Mail id</th>
    </tr>";

while ($row = mysqli_fetch_array($result)) {
        echo "<tr class=\"".(($row['id'] % 2 == 1)?"odd":"even")."\">";
        echo "<td>" . $row['id'] . "</td>";
        echo "<td>" . $row['name'] . "</td>";
        echo "<td>" . $row['username'] . "</td>";
        echo "<td>" . $row['mail'] . "</td>";
        echo "</tr>";
}

echo "</table>";
于 2013-05-28T20:15:33.717 回答
0

改用这个:

$result = mysqli_query($con, "SELECT * FROM form1 ORDER by id   ");

echo "<table border=1>
    <tr>
    <th>id</th>
    <th>Name</th>
    <th>userName</th>
    <th>e-Mail id</th>
    </tr>";

$class = 'even';
while ($row = mysqli_fetch_array($result)) {
    $class = $class=='even' ? 'odd' : 'even';

        echo "<tr>";
        echo "<td class="' . $class . '">" . $row['id'] . "</td>";
        echo "<td class="' . $class . '">" . $row['name'] . "</td>";
        echo "<td class="' . $class . '">" . $row['username'] . "</td>";
        echo "<td class="' . $class . '">" . $row['mail'] . "</td>";
        echo "</tr>";
}

echo "</table>";
于 2013-05-28T20:14:52.150 回答
0

您不应该真正将 div 标签放在 tr 标签之外,最好将 class 属性设置为 tr 标签,例如

<tr class="odd">
于 2013-05-28T20:15:15.437 回答