How can variables from a database be replaced in PHP scripts for email templates?

To replace variables from a database in PHP scripts for email templates, you can retrieve the necessary data from the database and then use string replacement functions to insert the variables into the email template. This can be achieved by querying the database for the required information, storing it in variables, and then using str_replace() or sprintf() functions to replace placeholders in the email template with the retrieved data.

// Assume $db is the database connection and $emailTemplate is the email template string
// Retrieve necessary data from the database
$query = "SELECT name, email FROM users WHERE id = 123";
$result = mysqli_query($db, $query);
$row = mysqli_fetch_assoc($result);

// Store data in variables
$name = $row['name'];
$email = $row['email'];

// Replace variables in email template
$subject = "Hello, %s";
$body = "Dear %s, your email address is %s. Thank you for your support.";

$subject = sprintf($subject, $name);
$body = sprintf($body, $name, $email);

// Send email
// mail($email, $subject, $body);