What are some best practices for linking data from a MySQL database to a table in PHP?

When linking data from a MySQL database to a table in PHP, it is best practice to establish a connection to the database using mysqli or PDO, retrieve the data using a query, and then loop through the results to populate the table with the data.

<?php
// Establish a connection to the MySQL database
$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);
}

// Retrieve data from the database
$sql = "SELECT * FROM table";
$result = $conn->query($sql);

// Populate the table with the data
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "<tr><td>" . $row["column1"] . "</td><td>" . $row["column2"] . "</td></tr>";
    }
} else {
    echo "0 results";
}

// Close the connection
$conn->close();
?>