What are the potential pitfalls of directly outputting MySQL data into an HTML table using PHP?

Directly outputting MySQL data into an HTML table using PHP without proper sanitization can lead to security vulnerabilities such as SQL injection attacks. To prevent this, it is important to use prepared statements or parameterized queries to safely retrieve and display data from the database.

<?php
// Establish a connection to the database
$connection = new mysqli("localhost", "username", "password", "database");

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

// Prepare a SQL query using a prepared statement
$query = $connection->prepare("SELECT column1, column2 FROM table");
$query->execute();
$query->bind_result($column1, $column2);

// Output the data in an HTML table
echo "<table>";
echo "<tr><th>Column 1</th><th>Column 2</th></tr>";
while ($query->fetch()) {
    echo "<tr><td>" . htmlspecialchars($column1) . "</td><td>" . htmlspecialchars($column2) . "</td></tr>";
}
echo "</table>";

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