What are some common pitfalls when trying to display database values in a table using PHP?

One common pitfall when displaying database values in a table using PHP is not properly escaping the data, which can lead to security vulnerabilities like SQL injection. To solve this issue, always use prepared statements or parameterized queries to safely retrieve and display data from the database.

<?php
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare a SQL statement
$stmt = $pdo->prepare("SELECT * FROM mytable");

// Execute the statement
$stmt->execute();

// Display the data in a table
echo "<table>";
echo "<tr><th>ID</th><th>Name</th></tr>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo "<tr><td>" . htmlspecialchars($row['id']) . "</td><td>" . htmlspecialchars($row['name']) . "</td></tr>";
}
echo "</table>";
?>