What best practices should be followed when integrating PHP variables with MySQL database data in HTML tables?

When integrating PHP variables with MySQL database data in HTML tables, it is important to properly sanitize and escape the data to prevent SQL injection attacks. Additionally, using prepared statements can help improve performance and security by separating SQL logic from data. Finally, consider using a loop to dynamically populate the table with data fetched from the database.

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

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

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

// Create HTML table
echo "<table>";
echo "<tr><th>Column 1</th><th>Column 2</th></tr>";
while ($row = mysqli_fetch_assoc($result)) {
    echo "<tr><td>" . htmlspecialchars($row['column1']) . "</td><td>" . htmlspecialchars($row['column2']) . "</td></tr>";
}
echo "</table>";

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