2012-08-05 16 views
1

我已經使用PHP從MYSQL數據庫建立了一個表。有4列檢查它們是否有yes,並且只有如此才顯示。唯一的問題是,當第一列repair什麼都沒有,但後續列有yes時,它們顯示將yes輸出到repair列中,而不是在那裏留下空白處並將其放在正確的列下。列標題正確顯示,它只是讓數據顯示在正確的列中。不知道如何去這個,所以任何幫助表示讚賞。間距與if語句不工作PHP MySQL

//build table for results 
echo "<table><tr>"; 
echo "<th>Part Number</th>"; 
echo "<th>Serial Number</th>"; 
echo "<th>Date</th>"; 

//check whether each element has data 
//and only display is data present 
if ($repair=="yes") echo "<th>Repair</th>"; 
if ($upgrade=="yes") echo "<th>Upgrade</th>"; 
if ($pm=="yes") echo "<th>PM</th>"; 
if ($nofault=="yes") echo "<th>No Fault</th></tr>"; 

// printing table rows 
while($row = mysql_fetch_array($result)) 
{ 
$part=$row['part']; 
$serial=$row['serial']; 
$date=$row['date']; 
$Repair=$row['repair']; 
$Upgrade=$row['upgrade']; 
$PM=$row['pm']; 
$NoFault=$row['nofault']; 

echo "<tr>"; 
echo "<td>$part</td>"; 
echo "<td>$serial</td>"; 
echo "<td>$date</td>"; 
if ($Repair=="yes") echo "<td>YES</td>"; 
if ($Upgrade=="yes") echo "<td>YES</td>"; 
if ($PM=="yes") echo "<td>YES</td>"; 
if ($NoFault=="yes") echo "<td>YES</td>"; 
echo "</tr>"; 
} 

echo "</table>"; 

回答

1

當if計算結果爲false時,應該包含空單元格。像這樣:

if ($Repair == "yes") { 
echo "<td>yes</td>" 
} else { 
echo "<td></td>" 
} 

你也可以在這種情況下直接在td回顯值。事情是這樣的:

echo "<td>"; 
if ($Repair == "yes") echo $Repair; 
echo "</td>"; 
+0

謝謝你的作品真的很好。在附註中,我現在有空白列,我可以更改我的CSS或PHP,使它的寬度很小,所以它沒有太大差距嗎?此刻我的桌子寬度全部是自動間距。 – Hux 2012-08-05 02:02:28

+0

其實已經排序。謝謝你的幫助。 – Hux 2012-08-05 02:14:39

1

這種邏輯可能有助於

if ($repair=="yes") echo "<th>Repair</th>" else echo "<th>&nbsp;</th>"; 

下相同的代碼

if ($Repair=="yes") echo "<td>YES</td>" else echo "<td>&nbsp;</td>"; 
+0

感謝您的幫助。 – Hux 2012-08-05 02:02:55

1

您需要輸出<td></td>兩種方式。你正在使用的代碼風格是一個可怕的混亂(雙引號的HTML字符串噸回聲陳述)。這裏有一個更好的方法:

//build table for results 

?> 

<table> 

<tr> 
<th>Part Number</th> 
<th>Serial Number</th> 
<th>Date</th> 

<?php 

//check whether each element has data 
//and only display is data present 
if ($repair=="yes") echo "<th>Repair</th>"; 
if ($upgrade=="yes") echo "<th>Upgrade</th>"; 
if ($pm=="yes") echo "<th>PM</th>"; 
if ($nofault=="yes") echo "<th>No Fault</th></tr>"; 

// printing table rows 
while($row = mysql_fetch_array($result)) { 

?> 

<tr> 

<td><?php echo $part; ?></td> 

<td><?php echo $serial; ?></td> 

<td><?php echo $date; ?></td> 

<td><?php echo $row[ 'Repair' ] == "yes" ? "YES" : ""; ?></td> 

<td><?php echo $row[ 'Upgrade' ] == "yes" ? "YES" : ""; ?></td> 

<td><?php echo $row[ 'PM' ] == "yes" ? "YES" : ""; ?></td> 

<td><?php echo $row[ 'NoFault' ] == "yes" ? "YES" : ""; ?></td> 

</tr> 

<?php 

} 
// while 

?> 

</table>