2012-06-01 76 views
0

我正在寫一個小型購物車,目前正面臨着如何將MySQL表結果顯示到列表顯示中的問題。我有一個代碼完成整個數據庫搜索並返回結果,我的問題顯示了像大多數購物車一樣的結果。使用php以表格形式回顯mysql查詢結果

這是我想達到的一個例子。

<table> 

<tr> 
<td>First mysql result row comes here</td> 
<td>Second Mysql result row comes here</td> 
</tr> 


<tr> 
<td>third mysql result row comes here</td> 
<td>fourth Mysql result row comes here</td> 
</tr> 

</table> 

請注意,它每行顯示兩個<td>

我很難找到答案。可以用css來完成嗎?

回答

3
<table> 
<?php 
$tr = false; 

foreach($results_from_database as $result) { 
    $tr = !$tr; 

    if($tr) { 
     echo '<tr>'; 
    } 

    echo "<td>$result</td>"; 

    if(!$tr) { 
     echo '</tr>'; 
    } 
} 

// if there's odd amount of results, add an empty cell and close the tr tag 
if($tr) { 
    echo '<td></td></tr>'; 
} 
?> 
</table> 
+0

我收到一條錯誤消息,說foreach內聯的無效參數..... – jcobhams

+0

嗯,是的,我只用了一個佔位符。您應該用您用來查看查詢結果的實際循環替換它。 – JJJ