Building a dynamic site – Part 2

Continuing from “Building a dynamic site Part 2”, this article will go over building the php script that will take your page from the database, and insert it into the template, and output it to the user.

If you forgot to make a template, go back now and create one. Below is the PHP code we will be using to make our dynamic site:

<?
$global_dbh = mysql_connect("localhost","username","password");
mysql_select_db("mydatabasename", $global_dbh);

$query = "SELECT * FROM `pages` WHERE `PID`=’$id’";
$result = mysql_query($query, $global_dbh);
$row = mysql_fetch_array($result);

$file = file_get_contents("template.txt");

$file = str_replace("##TITLE##", $row["Title"], $file);
$file = str_replace("##BODY##", $row["Body"], $file);

echo $file;
?>

This is simply the opening PHP tag. It tells the server that what follows is PHP.

$global_dbh = mysql_connect("localhost","username","password");

This creates a connection to the MySQL server, and assigns a handle to $global_dbh. Simply replace username and password with your username and password for MySQL.

mysql_select_db("mydatabasename", $global_dbh);

This tells MySQL which database you’ll be using. Change mydatabasename to your actual database name.

$query = "SELECT * FROM `pages` WHERE `PID`='$id'";

This is the MySQL query we are going to be using. When we access the script its going to be page.php?id=## – The number is the Page ID used in the database.

$result = mysql_query($query, $global_dbh);

This line actually runs the query on the MySQL server.

$row = mysql_fetch_array($result);

This line takes the table row that was selected in the previous line, and assigns it as an array to $row

$file = file_get_contents("template.txt");

This gets the contents of your template file.

$file = str_replace("##TITLE##", $row["Title"], $file);

This inserts the TITLE of the page where you put ##TITLE## in your template.

$file = str_replace("##BODY##", $row["Body"], $file);

This inserts the BODY of the page where you put ##BODY## in your template.

echo $file;

This outputs the results to the browser

?>

This tells the server that the PHP code has ended.

This script is very simple, but you should be able to get the idea and add more rows to your database, and more variables into the template. Just keep adding more replace lines.

In “Building a dynamic site – Part 3” we will go over how to create an index page that links to all your pages in your database.