Azoni Azoni - 2 months ago 11
HTML Question

How to write data into multiple HTML table columns with PHP?

I made this code write data into an HTML table:

<?php
//DB Verbindung
$con = mysqli_connect("localhost","root","","altislife");
$header = -1;
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql="SELECT * FROM players";

if ($result=mysqli_query($con,$sql))
{
echo "<thead><tr>";
while ($fieldinfo=mysqli_fetch_field($result))
{
echo "<th>$fieldinfo->name</th>";
$header++;
echo "$header";
}
echo "</tr></thead>";
mysqli_free_result($result);
}

if ($result=mysqli_query($con,$sql))
{
echo "<tbody>";
for ($i=0; $i < $header; $i++) {
while($sql = mysqli_fetch_array($result))
{
echo "<tr><td>" . $sql[$i] . "</td><td> ";
}
}
echo "</tbody>";
}

mysqli_close($con);


The problem is that it only fills the first column.

Then I tried this:

<?php
//DB Verbindung
$con = mysqli_connect("localhost","root","","altislife");
$header = -1;
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql="SELECT * FROM players";

if ($result=mysqli_query($con,$sql))
{
echo "<thead><tr>";
while ($fieldinfo=mysqli_fetch_field($result))
{
echo "<th>$fieldinfo->name</th>";
$header++;
echo "$header";
}
echo "</tr></thead>";
mysqli_free_result($result);
}

if ($result=mysqli_query($con,$sql))
{
echo "<tbody>";
while($sql = mysqli_fetch_array($result))
{
for ($i=0; $i < $header; $i++) {
echo "<tr><td>" . $sql[$i] . "</td><td> ";
}
}
echo "</tbody>";
}

mysqli_close($con);


The problem with this code is the same as with the first example.
Can anyone see my mistake?

Answer
if ($result=mysqli_query($con,$sql))
{
    $row = mysqli_fetch_assoc($result);
    $html = '<table><tr><th>'.implode('</th><th>',array_keys($row)).'</th></tr>';
    do {
       $html .= '<tr><td>'.implode('</td><td>',$row).'</td></tr>';
    }while($row = mysqli_fetch_assoc($result));
    $html .='</table>';
}
echo $html;

Try it this way, and figure out how this works ;-)

Points to your code:

  • tbody is not table yours frist example has no table tags
  • a row in a table is defined with <tr></tr> your second example misses a close tag
  • thead and tbody are optional and have no impact on the html

Last point: it is unnesessary to run the sql twice to generate a table

implode($sep,$arr) implode takes too args and seperator like <th></th> and merges all entries of an array with is like: array('a','b','c') becomes a<th></th>b<th></th>c

mysqli_fetch_assoc vs mysqli_fetch_array second gives something like [0=>'a',1=>'b'] and the first ['name'=>'a','color'=>'b']

Comments