How can a while loop in PHP affect the repetition of column names in a table?

When using a while loop in PHP to fetch data from a database and display it in a table, the column names can be repeated for each row of data displayed. To solve this issue, you can use a conditional statement to only display the column names once before the while loop starts fetching and displaying the data.

<?php
// Assume $result is the result set from a database query

// Display table header with column names
echo "<table>";
echo "<tr>";
if ($row = $result->fetch_assoc()) {
    foreach ($row as $key => $value) {
        echo "<th>$key</th>";
    }
    echo "</tr>";

    // Display data rows
    do {
        echo "<tr>";
        foreach ($row as $value) {
            echo "<td>$value</td>";
        }
        echo "</tr>";
    } while ($row = $result->fetch_assoc());
} else {
    echo "<tr><td colspan='2'>No results found</td></tr>";
}
echo "</table>";
?>