How can placeholders in a document template be replaced with data from a MySQL database using PHP to create personalized letters efficiently?

To replace placeholders in a document template with data from a MySQL database using PHP, you can retrieve the necessary data from the database and then use str_replace() function to replace the placeholders with the data. This can be done efficiently by looping through the database results and replacing placeholders in the template for each record.

<?php
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Retrieve data from database
$sql = "SELECT * FROM customers";
$result = $conn->query($sql);

// Template with placeholders
$template = "Hello {name},\nThank you for your purchase of {product}.";

// Loop through database results
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $letter = $template;
        $letter = str_replace("{name}", $row["name"], $letter);
        $letter = str_replace("{product}", $row["product"], $letter);

        // Output personalized letter
        echo $letter . "\n\n";
    }
} else {
    echo "0 results";
}

$conn->close();
?>