What are common pitfalls when using PHP to generate HTML tables from database entries?

One common pitfall when using PHP to generate HTML tables from database entries is not properly escaping the data, which can lead to security vulnerabilities such as SQL injection attacks. To solve this issue, always use prepared statements or escape the data before outputting it in the HTML table.

// Connect to database
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Retrieve data from database
$stmt = $pdo->query("SELECT * FROM mytable");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Output data in HTML table
echo "<table>";
echo "<tr><th>Name</th><th>Email</th></tr>";
foreach ($rows as $row) {
    echo "<tr><td>" . htmlspecialchars($row['name']) . "</td><td>" . htmlspecialchars($row['email']) . "</td></tr>";
}
echo "</table>";