What are some best practices for displaying data from a database in PHP?

When displaying data from a database in PHP, it is important to properly sanitize the data to prevent SQL injection attacks. One best practice is to use prepared statements with parameterized queries to securely interact with the database. Additionally, consider using a loop to iterate through the retrieved data and display it in a structured format on the webpage.

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

// Prepare a SQL query
$stmt = $pdo->prepare('SELECT * FROM mytable');
$stmt->execute();

// Fetch and display the data
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo '<p>Name: ' . htmlspecialchars($row['name']) . '</p>';
    echo '<p>Email: ' . htmlspecialchars($row['email']) . '</p>';
}