How can PHP be used to output database results directly as an HTML table?

To output database results directly as an HTML table using PHP, you can fetch the data from the database, loop through the results, and echo out the data within HTML table tags. This way, you can dynamically generate an HTML table with the database results.

<?php
// Connect to the database
$conn = new mysqli('localhost', 'username', 'password', 'database');

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Fetch data from the database
$result = $conn->query("SELECT * FROM table_name");

// Output data as HTML table
echo "<table>";
while($row = $result->fetch_assoc()) {
    echo "<tr>";
    foreach($row as $value) {
        echo "<td>" . $value . "</td>";
    }
    echo "</tr>";
}
echo "</table>";

// Close database connection
$conn->close();
?>