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