php echo table with while loop

与世无争的帅哥 提交于 2019-12-04 19:04:33

First off, you should learn the HTML code for tables. Your code is putting a Table Header (th) next to a normal column item (td). You need to loop through the headers first then next row loop through the column items or build the strings to echo out.

$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>";

Your structure is creating a TH then a TD and then a TH and then a TD etc.

This isn't how you create a table, you first need to make the four TH's and THEN you can make the four TD's.

Edit: Marko D has supplied the code to explain what I mean.

First collect table header and body, and then output them. The way you were doing, html was like this, I guess it's easy to see what is wrong with html

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

What you need is this:

$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>';

You need to write all usernames in <th>-tags. I'd put it in an array first, and from the array into the table...

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!