Have you ever been annoyed by template engines that force you to keep your templates in flat files? Ever feel like that Content Management System you just created isn't as dynamic as you originally thought? If you have ever felt like this, you may benefit from having your templates in a database.
First, let's decide on our database structure. For what we need to do, we only require one table, which will be called "templates," which will contain -- yes, you guessed it -- our templates. It's a very simple table and only has 3 fields.
templateid: This is a unique identifier for the template.
name: Pretty self explanatory, the name of the template.
content: Again, pretty obvious, this is the HTML that makes up the template.
To create this table, you can use the following SQL:
CREATE TABLE `templates` ( `templateid` int(10) NOT NULL auto_increment, `name` varchar(30) NOT NULL default '', `content` text NOT NULL, PRIMARY KEY (`templateid`) ) TYPE=MyISAM AUTO_INCREMENT=1 ;
Now we will populate it. We will only have 2 records, page_header & page_footer. These will be used to display the <html>, <head> and other needed tags in the page. This is simple so that you can understand what is happening, in reality, these would include logos, menus, and other elements. The advantage of this is that there is only one place where you edit the layout of your page, instead of having to do it in each HTML file. Anyway, here's the SQL:
INSERT INTO `templates` VALUES (1, 'page_header', '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">rn<html>rn<head>rn <title>$pageTitle</title>rn</head>rn<body>'); INSERT INTO `templates` VALUES (2, 'page_footer', '</body>rn</html>');
Let's go through page_header, which consists of the following html:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>$pageTitle</title> </head> <body>
As you can see, this includes a PHP variable, $pageTitle. These will be defined in the code before we display the template. But we'll talk about that later. Now we have the database schema ready, we can start the basic functions for grabbing the template from the database.
template.php
The following code is in the file 'template.php':
<?php
function fetchTemplate ($templateName) {
$Query = "select content from templates where name='$templateName'"; $tRes = mysql_query($Query); $Template = mysql_fetch_array($tRes);