php echo table with while loop

一笑奈何 提交于 2019-12-06 10:06:36

问题


I am creating a table and want it laid out a certain way and have to retrieve the data from the DB. I am trying to get it set up where it has the usernames across the top example...

 Jim     Chris     Allen    Rick
 7       8          4         5

my code looks like this and I have been messing around with it for hours and cant figure out why I cant get it set up how I want. Any help would be appreciated. Its a while loop.

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

回答1:


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



回答2:


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.




回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/15140016/php-echo-table-with-while-loop

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