简体   繁体   中英

How can I get data with column names in the same table from SQL using PHP?

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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM