What are some potential pitfalls when using PHP to output data from a database in a table format?

One potential pitfall when using PHP to output data from a database in a table format is not properly escaping user input, which can lead to SQL injection attacks. To solve this issue, always use prepared statements or parameterized queries to safely retrieve and display data from the database.

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

// Prepare and execute a query to retrieve data from the database
$stmt = $pdo->prepare('SELECT * FROM mytable');
$stmt->execute();

// Output data in a table format
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>';