1

I'm trying to show a full table from SQL in my HTML/PHP webpage. So far I succeeded to fetch the data from the table in my webpage without define each row in HTML. This works, but it shows the data from the table only. I want to see the column names in the first row.

See my code below:

include_once "connection.php";
$sql = "SELECT * FROM `own`";
$result = mysqli_query($conn, $sql);

echo "<br>";
echo "<table border='1'>";

while ($row = mysqli_fetch_assoc($result)) 
{ 
  echo "<tr>";
  foreach($row as $value) { 
    echo "<td>" . $value . "</td>"; 
  }
  echo "</tr>";
}
echo "</table>";

2 Answers 2

1

As you are using mysqli_fetch_assoc() - this will return an array with the column names as the key for each value. So this code will display (for the first loop only) the column names as a separate row.

$headerDisplayed = false;

while ($row = mysqli_fetch_assoc($result))
{
    if ( $headerDisplayed == false )    {
        echo "<tr>";
        foreach($row as $columnName => $value) {
            echo "<th>" . $columnName . "</th>";
        }
        echo "</tr>";
        $headerDisplayed = true;
    }
    echo "<tr>";
    foreach($row as $value) {
        echo "<td>" . $value . "</td>";
    }
    echo "</tr>";
}

If you want to be able to give a more meaningful name, you could also use column aliases (for example)..

select `dept_no` as `department number` from `departments`

will show department number as the heading instead of dept_no.

Sign up to request clarification or add additional context in comments.

Comments

1

The easiest solution would be to just output the column names first on the first iteration:

while ($row = mysqli_fetch_assoc($result)) 
{ 
    // If the variable $colNamesPrinted is undefined, print the column names
    if (isset($colNamesPrinted) === false) {
        echo "<tr>";
        foreach($row as $name => $value) { 
            echo "<th>" . $name . "</th>"; 
        }
        echo "</tr>";

        // Define the variable so it will be set on the next iteration.
        $colNamesPrinted = true;
    }

    echo "<tr>";
    foreach($row as $value) { 
        echo "<td>" . $value . "</td>"; 
    }
    echo "</tr>";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.