What are some common pitfalls to avoid when displaying database data in HTML tables using PHP?
One common pitfall to avoid when displaying database data in HTML tables using PHP is not properly escaping the data to prevent SQL injection attacks. To solve this issue, always use prepared statements when querying the database and sanitize user input before displaying it in the table.
<?php
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a statement to query the database
$stmt = $pdo->prepare('SELECT * FROM mytable');
$stmt->execute();
// Display the data in an HTML table
echo '<table>';
echo '<tr><th>ID</th><th>Name</th><th>Email</th></tr>';
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<tr>';
echo '<td>' . htmlspecialchars($row['id']) . '</td>';
echo '<td>' . htmlspecialchars($row['name']) . '</td>';
echo '<td>' . htmlspecialchars($row['email']) . '</td>';
echo '</tr>';
}
echo '</table>';
?>