What are some best practices for displaying data in a table using PHP and MySQL?

When displaying data in a table using PHP and MySQL, it is important to properly handle the data retrieval and formatting to ensure a clean and organized display. One best practice is to use a loop to fetch data from the database and populate the table rows dynamically. Additionally, consider using CSS to style the table for better readability and user experience.

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

// Check connection
if ($connection === false) {
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Fetch data from database
$query = "SELECT * FROM table_name";
$result = mysqli_query($connection, $query);

// Display data in a table
echo "<table>";
while ($row = mysqli_fetch_array($result)) {
    echo "<tr>";
    echo "<td>" . $row['column1'] . "</td>";
    echo "<td>" . $row['column2'] . "</td>";
    echo "<td>" . $row['column3'] . "</td>";
    echo "</tr>";
}
echo "</table>";

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