php echo表与while循环

时间:2013-02-28 16:00:04

标签: php mysql while-loop html-table

我正在创建一个表,并希望它以某种方式布局,并且必须从数据库中检索数据。我试图让它设置在顶部示例中具有用户名的地方......

 Jim     Chris     Allen    Rick
 7       8          4         5

我的代码看起来像这样,我已经搞乱了几个小时,无法弄清楚为什么我不能设置我想要的。任何帮助,将不胜感激。它是一个循环。

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

4 个答案:

答案 0 :(得分: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>";

答案 1 :(得分: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>';

答案 2 :(得分:0)

您的结构正在创建TH然后是TD,然后是TH,然后是TD等。

这不是你如何创建一个表格,你首先需要制作四个TH,然后才能制作四个TD。

编辑:Marko D提供了解释我的意思的代码。

答案 3 :(得分: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