What are some best practices for displaying data from a database in a template using PHP?
When displaying data from a database in a template using PHP, it is important to sanitize the data to prevent SQL injection attacks and ensure proper formatting for display. One best practice is to use prepared statements to safely retrieve data from the database and then loop through the results to display them in the template.
<?php
// Connect to the database
$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();
// Fetch the results as an associative array
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Loop through the results and display them in the template
foreach ($results as $row) {
echo '<div>';
echo '<h2>' . htmlspecialchars($row['title']) . '</h2>';
echo '<p>' . nl2br(htmlspecialchars($row['content'])) . '</p>';
echo '</div>';
}
?>