How can PHP be used to display MySQL table data in a formatted table?

To display MySQL table data in a formatted table using PHP, you can first establish a connection to the MySQL database, retrieve the data from the table using a SQL query, and then iterate through the data to display it in an HTML table format.

<?php
// Establish connection to MySQL database
$connection = mysqli_connect("hostname", "username", "password", "database");

// Check connection
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

// Retrieve data from MySQL table
$sql = "SELECT * FROM table_name";
$result = mysqli_query($connection, $sql);

// Display data in a formatted table
echo "<table border='1'>";
echo "<tr><th>ID</th><th>Name</th><th>Email</th></tr>";
while ($row = mysqli_fetch_assoc($result)) {
    echo "<tr><td>" . $row['id'] . "</td><td>" . $row['name'] . "</td><td>" . $row['email'] . "</td></tr>";
}
echo "</table>";

// Close connection
mysqli_close($connection);
?>