Are there best practices for creating a template engine in PHP to insert database values into HTML templates?
When creating a template engine in PHP to insert database values into HTML templates, it is important to separate the logic from the presentation layer. One way to achieve this is by using placeholders in the HTML template that will be replaced with the database values. Additionally, it is recommended to sanitize the database values before inserting them into the template to prevent SQL injection attacks.
<?php
// Sample code to demonstrate inserting database values into an HTML template using a template engine
// Connect to the 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);
}
// Fetch data from the database
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
// Load the HTML template
$template = file_get_contents('template.html');
// Loop through the database results and insert them into the template
while($row = $result->fetch_assoc()) {
$output = str_replace('{name}', $row['name'], $template);
$output = str_replace('{email}', $row['email'], $output);
// Output the final HTML
echo $output;
}
// Close the database connection
$conn->close();
?>