What are the best practices for displaying query results in PHP from a MySQL database?

When displaying query results in PHP from a MySQL database, it is important to properly handle the data to ensure security and readability. One common approach is to use a loop to iterate through the results and display them in a table format on the webpage. Additionally, it is recommended to sanitize the data to prevent SQL injection attacks.

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

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

// Perform a query
$query = "SELECT * FROM table_name";
$result = mysqli_query($connection, $query);

// Display results in a table format
echo "<table>";
while ($row = mysqli_fetch_assoc($result)) {
    echo "<tr>";
    foreach ($row as $key => $value) {
        echo "<td>" . $key . ": " . $value . "</td>";
    }
    echo "</tr>";
}
echo "</table>";

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