MySQL数据的不同表格单元格颜色

时间:2013-04-01 19:40:47

标签: php css mysql html-table

我想为不同的MySQL数据更改表格单元格的背景颜色。我的情况是当用户输入他们的体重和身高时,它将计算他们的体重指数(BMI)以及输出BMI类别。像这样:

BMItable

现在如何更改BMI类别的表格单元格颜色,其中“体重不足”为白色,“正常体重”为黄色,“超重”为橙色?我尝试过以下但不起作用。

这就是我在PHP代码中的内容:

echo "<table border=\"1\"><tr><th>Name</th> //etc.
if (mysqli_num_rows($result) == 0)
echo "<tr><td colspan='2'>No records found.</td></tr>";

else {
while ($row = mysqli_fetch_assoc($result)) 
 {
 echo "<tr><td>" . $row['Name'] . "</td>"; 
 //some more codes for weight, height, BMI
 echo "<td class='<?php $tdClass; ?>'>" . $row['Health_Measure'] . "</td>";
 }
}
echo "</table>";

if ($row['Health_Measure'] == "Underweight") 
        $tdClass = 'underweight';

else if ($row['Health_Measure'] == "Normal Weight") 
    $tdClass = 'normalweight';

else if ($row['Health_Measure'] == "Overweight") 
    $tdClass = 'overweight';

CSS:

.underweight {
    background-color:white;
}
.normalweight {
    background-color:yellow;
}
.overweight {
    background-color:orange;
}

2 个答案:

答案 0 :(得分:3)

分配$ tdClass变量的代码位于使用$ tdClass变量的循环之后,因此td标记将没有正确的类。把它改成这个......

    echo "<table border=\"1\"><tr><th>Name</th> //etc.
if (mysqli_num_rows($result) == 0)
echo "<tr><td colspan='2'>No records found.</td></tr>";

else {
while ($row = mysqli_fetch_assoc($result)) 
 {
    if ($row['Health_Measure'] == "Underweight") 
        $tdClass = 'underweight';

else if ($row['Health_Measure'] == "Normal Weight") 
    $tdClass = 'normalweight';

else if ($row['Health_Measure'] == "Overweight") 
    $tdClass = 'overweight';

 echo "<tr><td>" . $row['Name'] . "</td>"; 
 //some more codes for weight, height, BMI
 echo "<td class='<?php $tdClass; ?>'>" . $row['Health_Measure'] . "</td></tr>";
 }
}
echo "</table>";

答案 1 :(得分:0)

您只需移动代码以确定输出表行的循环内的TD的CSS类。