Template based web sites allow you to produce dynamic web content and give your visitors the appearance that each page on your site is different. In this article James shows us how to implement a template based web site using two methods: a MySQL database and a flat file approach.
Implementing a Template Based Web Site With PHP - The PHP Code (Page 4 of 5 )
Our demonstration PHP page is going to return the HTML for ResultsPage, along with a table full of results (with title and hits columns) using the information from the database. If you want to create the table and dummy data for the database, use the following MySQL statement:
CREATE TABLE items (
id int unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY,
The code is actually very simple: it sets a few variables, loads the data from a template, and then outputs the data. However, it's those eval statements that do all the hard work and need looking at more closely.
first. What the eval statement does is evaluate PHP code as if you have written it yourself. For example
does the same as hard-coding
Our code takes advantage of this functionality, by writing it's own php code for this statement. What's the point, you may ask? Well, just as
echo "hello $name";
would output hello and the contents of the variable, $name, the same applies when used within an eval statement. Lets imagine that the gettemplate function returns simply
What ends up being evaluated in the call to the eval statement is (remembering that we need to escape characters such as $ and " within the string):
$resultbits .= "<td>$data[title]</td>";
PHP then appends <td>$data[title]</td> to the $resultbits variable, and replaces $data[title] with its current value. In the same way, PHP replaces all the variables within our template with the current value, which, in this instance, has been loaded from $data=mysql_fetch_array($query).
Our code simply loops through the information from the database, evaluating the template for each different value of $data[title] and appending that value to $resultbits. Finally, once the loop is complete, we call another eval statement, this time retrieving the value from the ResultsPage template and replacing $pagetitle, $searchquery and $resultbits with their values in the script. Simple.