What are some best practices for incorporating database values into HTML output in PHP?

When incorporating database values into HTML output in PHP, it is important to properly sanitize the data to prevent any potential security vulnerabilities such as SQL injection attacks. One best practice is to use prepared statements when querying the database to ensure that user input is properly escaped. Additionally, it is recommended to use htmlspecialchars() function to escape any output data to prevent cross-site scripting attacks.

// Sample code snippet to fetch data from a database and output it safely in HTML

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

// Prepare a SQL statement
$stmt = $pdo->prepare("SELECT name, email FROM users WHERE id = :id");

// Bind parameters
$stmt->bindParam(':id', $_GET['id']);

// Execute the query
$stmt->execute();

// Fetch the data
$user = $stmt->fetch();

// Output the data safely in HTML
echo "<div>Name: " . htmlspecialchars($user['name']) . "</div>";
echo "<div>Email: " . htmlspecialchars($user['email']) . "</div>";