What are some best practices for dynamically loading tables from a database in PHP?

When dynamically loading tables from a database in PHP, it is important to use prepared statements to prevent SQL injection attacks and to handle errors gracefully. Additionally, it is recommended to fetch the data from the database using a loop and display it in an HTML table format for better readability.

<?php
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

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

// Prepare and execute a SQL query
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);

// Display the data in an HTML table
if ($result->num_rows > 0) {
    echo "<table>";
    while($row = $result->fetch_assoc()) {
        echo "<tr>";
        foreach($row as $value) {
            echo "<td>" . $value . "</td>";
        }
        echo "</tr>";
    }
    echo "</table>";
} else {
    echo "0 results";
}

$conn->close();
?>