1

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

BMI表

现在如何更改 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;
}
4

2 回答 2

3

Your code to assign the $tdClass variable is after the loop that uses the $tdClass variable, so the td tags won't have the right classes. Change it to this...

    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>";
于 2013-04-01T19:49:10.870 回答
0

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

于 2013-04-01T19:43:24.863 回答