What are some best practices for replacing placeholders in templates with database values in PHP?

When replacing placeholders in templates with database values in PHP, it is important to securely retrieve the data from the database and properly sanitize it to prevent SQL injection attacks. One common approach is to use prepared statements to fetch data from the database and then replace placeholders in the template with the retrieved values.

// Assume $db is a PDO object connected to the database
// $template is the template string with placeholders

$stmt = $db->prepare("SELECT column_name FROM table_name WHERE condition = ?");
$stmt->execute([$condition]);
$data = $stmt->fetch(PDO::FETCH_ASSOC);

foreach ($data as $key => $value) {
    $template = str_replace("{{" . $key . "}}", $value, $template);
}

echo $template;