Website structure 3
htmlpage.class.php - HTMLPage class extended with database support
<?php
class HTMLPage {
var $title;
var $content;
var $id;
function HTMLPage() {
// If no page is selected default to frontpage (id=1)
$this->id = is_int($_GET["id"]) ? $_GET["id"] : 1;
// Connect to database and fetch title and content
$conn = mysql_connect("localhost", "your_username", "your_password");
mysql_select_db("cms");
$res = mysql_query("SELECT title,content FROM pages WHERE ID=". $this->id ." LIMIT 1");
// Make sure we found a page
if (mysql_num_rows($res) > 0) {
$page = mysql_fetch_array($res);
$this->title = $page["title"];
$this->content = $page["content"];
}
// Otherwise create a 404 page
else {
$this->title = '404 - Page not found';
$this->content = '
<h1>404 - Page not found</h1>
The page you requested could not be found.
';
}
}
function start() {
print '
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>'. $this->title .'</title>
</head>
<body>
';
}
function end() {
print '
</body>
</html>
';
}
function printContent() {
print $this->content;
}
}
?>
index.php - Database enabled template
<?php
// Include class file
include "htmlpage.class.php";
// Initiate HTMLPage object
$page =& HTMLPage();
$page->start();
$page->printContent();
$page->end();
?>
Dynamic menu
<?php
function printMenu() {
$res = mysql_query("SELECT id,title FROM pages ORDER BY id");
print '<ul>\n';
while ($item = mysql_fetch_array($res)) {
print '<li><a href="'. $_SERVER["PHP_SELF"] .'?id='. $item["id"] .'">'. $item["title"] .'</a>';
}
print '</ul>\n';
}
?>