What potential pitfalls should be considered when using PHP to output MySQL data in a table format?

One potential pitfall when outputting MySQL data in a table format using PHP is not properly escaping the data, which can lead to security vulnerabilities like SQL injection attacks. To mitigate this risk, it's important to use prepared statements or escape functions when querying and displaying data from the database.

<?php
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

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

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

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

// Output data in a table format
echo "<table>";
echo "<tr><th>ID</th><th>Name</th></tr>";
while($row = $result->fetch_assoc()) {
    echo "<tr><td>" . htmlspecialchars($row["id"]) . "</td><td>" . htmlspecialchars($row["name"]) . "</td></tr>";
}
echo "</table>";

$conn->close();
?>