2013-02-28 48 views
2

我正在創建一個表,並希望它以某種方式佈局,並且必須從數據庫中檢索數據。我試圖把它建立在那裏它在頂部例如用戶名...PHP回聲表與while循環

 
Jim  Chris  Allen Rick 
7  8   4   5 

我的代碼看起來是這樣的,我一直與它搞亂兜了幾個小時無法弄清楚,爲什麼我不能得到它建立了我想要的。任何幫助,將不勝感激。它是一個while循環。

while ($pickresults= mysql_fetch_assoc($picksquery)) { 
//first row       
    echo '<th> '.$pickresults['username'].' </th> '; 
     echo ' <td> '.$pickresults['firstgame'].' </td> '; } 

回答

3

首先,你應該學習表格的HTML代碼。您的代碼將一個表格標題(th)放在普通列項目(td)的旁邊。您需要首先遍歷標題,然後通過列項目循環下一行,或者將字符串生成爲echo

$headers = $col = ""; 
while($pickresults= mysql_fetch_assoc($picksquery)){ 
    $headers .= "<th> {$pickresults['username']} </th>"; 
    $col .= "<td> {$pickresults['firstgame']} </td>"; 
} 

echo "<table><tr>$headers</tr><tr>$col</tr></table>"; 
+0

upvote爲甜和簡單 – michi 2013-02-28 16:14:56

0

首先收集表頭和身體,然後輸出它們。你在做的方式,HTML是這樣的,我想這是很容易看到什麼是錯的HTML

<th>name</th> 
<td>value></td> 
<th>another name</th> 
<td>another value</td> 

你需要的是這樣的:

$td = ''; 
$th = ''; 
while ($pickresults= mysql_fetch_assoc($picksquery)) {      
    $th .= '<th> '.$pickresults['username'].' </th> '; 
    $td .= '<td> '.$pickresults['firstgame'].' </td> '; 
} 
echo '<table><tr>' . $th . '</tr><tr>' . $td . '</tr>' . '</table>'; 
+0

不要忘了封閉''圍繞各行,或者這會不會是一個有效的'

'。 – 2013-02-28 16:06:05

+0

謝謝,我更新了我的答案 – 2013-02-28 16:10:13

+0

謝謝你們的幫助。 – Ricky 2013-02-28 16:14:18

0

你的結構是建立一個TH然後TD然後是TH,然後是TD等。

這不是你如何創建表格,你首先需要製作四個TH,然後你可以製作四個TD。

編輯:Marko D提供瞭解釋我的意思的代碼。

+0

非常感謝。這有很大幫助。將循環保存到一個數組就是金錢。 – Ricky 2013-02-28 16:08:09

0

你需要編寫所有的用戶名在<th>標籤都有效。 我把它放在一個數組首先,從陣列到表...

while ($pickresults= mysql_fetch_assoc($picksquery)) { 

    $picked[]=$pickresults; 

} 

echo "<table><tr>"; // create table and 1st row 

foreach ($picked as $pick) { 

    echo "<th>{$pick['username']}</th>"; // create 1st line headers 

} 

echo "</tr><tr>"; // close 1st row and open 2nd 

foreach ($picked as $pick) { 

    echo "<td>{$pick['firstgame']}</td>"; // create 2nd line... 

} 

echo "</tr></table>"; // close 2nd row and table