How can PHP be used to store and retrieve content for different templates in a database?
To store and retrieve content for different templates in a database using PHP, you can create a table in your database to store the template content along with a unique identifier for each template. You can then write PHP functions to insert content into the database for each template and retrieve the content when needed by querying the database based on the template identifier.
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "templates_db";
$conn = new mysqli($servername, $username, $password, $dbname);
// Function to insert content for a template into the database
function insertTemplateContent($templateId, $content) {
global $conn;
$sql = "INSERT INTO templates (template_id, content) VALUES ('$templateId', '$content')";
$conn->query($sql);
}
// Function to retrieve content for a template from the database
function getTemplateContent($templateId) {
global $conn;
$sql = "SELECT content FROM templates WHERE template_id = '$templateId'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
return $row['content'];
} else {
return "Template content not found";
}
}