2013-04-01 56 views
1

所以我想改變表格單元格的背景顏色以獲得不同的MySQL數據。我的情況是,當用戶輸入他們的體重和身高時,它會計算他們的體重指數(BMI)以及輸出BMI類別。事情是這樣的:MySQL數據的不同表格單元格顏色

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; 
} 
+0

它會生成正確的HTML嗎?一點都沒有?有什麼,但不是它應該是什麼? – andrewsi

+0

該類不適用於單元格? – 2013-04-01 19:42:27

+0

沒有錯誤和表格輸出就像它在圖片中一樣。它似乎不是應用tdClass –

回答

0

你只需要移動你的代碼,以確定CSS類爲TD在循環內,你輸出表格行。

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>"; 
+0

它仍然不顯示正確的背景顏色 –

+0

我看到你錯過了我已經添加到我的答案的結束tr標記。這可能不是問題。我會靜態地將類名應用於td標籤,並查看它是否有效......以幫助縮小範圍。 – SomeSillyName