How can PHP be used to create a data table from a MySQL database for a website?

To create a data table from a MySQL database for a website using PHP, you can establish a connection to the database, query the data you want to display in the table, and then loop through the results to generate the table HTML code.

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

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

// Query to select data from the database
$sql = "SELECT * FROM table_name";
$result = mysqli_query($connection, $sql);

// Generate the HTML table code
echo "<table>";
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 the connection
mysqli_close($connection);
?>