Working Wonders on the Web

Wanna make your Website really cook with fresh, up-to-the-minute data? A dynamic Website could do this for you without breaking a sweat. We show you how.


Day in and day out you’ve been working like a fiend, constantly updating your Web site and trying to keep it fresh and interesting. But no matter how hard you try, you just can’t seem to keep up with the explosive growth of the World Wide Web. “Hundreds of new Web sites get created every day,” you think to yourself. “And all my favorite Web sites are continuously adding fresh, new content.” How can you keep up with the competition? How do all these new pages get created? How do they get updated so fast? It isn’t as hard as you think. It just takes a basic understanding of a powerful concept — dynamic Web pages.

To illustrate the fact that dynamic Web pages are not that hard to create, this article is going to walk through the creation of a Web-based press release engine. Our Web site will merge press releases stored in a database with a templated Web page on the fly. If you have an understanding of HTML, you should be able to easily follow along with our example and create your own dynamic Web pages. To create this site, we will be using three powerful open source technologies: Apache, MySQL, and PHP. (See the sidebars about each of these technologies to learn more about them.)

MySQL: An Open Source Database Management System

Figure 1-KDE Tool KMySQL
Figure One: MySQL has browser-based GUIs to aid database management.

MySQL is a cross platform Relational Database Management System (RDMS).

What is a relational database? Think of a flat file of data that looks something like a spreadsheet. It would have row after row of information, and be divided up into columns as well. Add in a way to relate multiple flat files together, and provide a set of tools to ease the burden of adding to, editing, deleting and searching all this data.

In the relational database world, the columns and rows of data are referred to as tables. These tables can be related to each other by “keys” (common data elements), and the “tool” you use to manipulate the database is a programming language called SQL, Structured Query Language.

MySQL was created in 1995 by Michael Widenius, who worked for a Swedish company, TcX. TcX created MySQL as an in-house tool, which it later made available to the public. There is no licensing fee for MySQL running on Linux, although you do need to purchase a license to run it on Windows.

MySQL, like most Linux applications, is a predominantly command-line-based application, although several browser- based GUI’s and one really nice KDE GUI have been created to help you manage your databases. (See Figure One.)

Probably the most notable SQL feature missing from MySQL is transactions — which would give it the ability to wrap several SQL commands into one all or nothing command with commit and back-out features. Despite the fact that MySQL is not as feature-rich as some commercial products, its light weight and speed help make it a good choice when creating a dynamic Web site.

PHP: The Scripting Language Built With the Web in Mind

Since the earliest days of the Web, developers have been pushing scripting languages such as Perl to their limits. However, as the need for Web pages with more functionality and ever increasing complex design elements grows, the complexity of using Perl to create Web pages also grows.

Enter PHP. Conceived in 1994-95 by Rasmus Lerdorf, PHP was designed with the Web, and more importantly, Web designers in mind. PHP is an embedded scripting language, meaning that pieces of PHP code are embedded in the middle of HTML documents. The PHP code is executed on the server, allowing infusion of dynamic elements into HTML documents. This seemingly simple function means that a graphic designer can now create a page layout using whatever HTML editor he or she wants, and then hand off the page to a programmer who will then “infuse” it with PHP code to make it a dynamic Web page. It is no longer necessary for a graphic designer to be a programmer, or vice versa. Even better, PHP is both elegant and simple to use.

Apache: The Workhorse of The Web

The Apache Software Foundation defines the Apache server as a powerful, flexible, HTTP/1.1-compliant Web server. With nearly 60 percent of all Web servers on the Internet running Apache (according to a May 2000 Netcraft survey), one could argue it is THE Web server of the Internet.

Highly extensible, configurable, and flexible, it is hard to imagine that the Apache server couldn’t suit your needs. Apache runs on virtually every platform that can run a Web server. One nice feature of Apache is its ability to run many scripting languages (like PHP) as an Apache module. This allows the module to run in the same memory space as the Apache server, providing a substantial performance boost.

What is a Static Web site?

Before diving into dynamic Web page design, it’s useful to understand how simple static HTML pages function. Static Web pages are manually created, then saved and uploaded to the Web server. Once a static page has been uploaded, it must be modified and re-uploaded each time its content changes. Pages with links to or from this page may need to be modified as the content changes, too, and then uploaded to the server. One look at the front page of Slashdot or your favorite portal site will convince you that if those sites were done with static pages, each would require an army of programmers cranking out new pages at a blinding rate to stay current. There has to be a better way. There is — the “dynamic Web site.”

What is a Dynamic Web site?

Dynamic sites provide for each displayed Web page to be based upon a “template,” which is then merged with constantly changing content. The resulting page is shoved out the door, creating pages that look the same as static pages but actually aren’t.

The functionality provided by the dynamic template varies, but usually the template houses site-navigation functionality as well as creating the site’s look and feel. The constantly updating text is usually contained in a database. When a user requests a page, the information is pulled from the database and combined with a template, creating a Web page. With a little programming ingenuity, all the links to and from these dynamic pages can be created dynamically as well. So now, when you need to add a page, you simply add the text for the page to a database, and the Website basically updates itself. Cool. So that’s how they do it.

Why Dynamic Sites are Better

Once a dynamic site is up and running, the benefits really start to kick in. Since you now have a comparatively small number of template pages,as opposed to what previously may have been hundreds or even thousands of Web pages, maintenance is greatly simplified. The look of the site can be changed in no time at all simply by modifying its templates. Changes to the database’s content can be administered via HTML forms. This means you won’t have to wait for your Web designers to get back from snow boarding — you can have an administrative assistant change the page instantly, or even have an automatic feed set up so that the database is updated without manual intervention. Think about things like live stock quotes, or for our example, perhaps a massaged PR hot-feed.

Creating a Dynamic Site

So what is the best way to go about creating your own dynamic site, then? First you need to have a Web server. Chances are you already have one. If you don’t, the Apache server is a great choice for all the obvious reasons. (See the Apache: The Workhorse of The Web sidebar, pg. 66)

Next, we need to decide how we are going to store the content we will display. In this example, we create a database to hold it using the MySQL database. (See the Creating a Simple Database Using MySQL sidebar, pg. 68, for step-by-step details on how to do this.)

A decent database allows us to split the content into database tables, with each table consisting of fields. Tables are rows and columns of data, while a field is a discrete piece of data in a table. So, for instance, we may create a table called newsitems, with fields such as title, date, fullstory, and author. It helps to visualize a database table as a spreadsheet. The columns across the top are the different fields, and each row of the sheet contains the entries. MySQL is perfect for creating such a database: it’s lightweight, fast, free under Linux, and is rapidly growing in popularity.

After that, we need to create our dynamic template pages. A great technology for building these templates is PHP (which stands for “Personal Home Pages” — please refer to the Creating Dynamic Web Pages Using PHP sidebar for more information on this topic). Conceptually, what we need to do is create two Web page templates — one will display links to all the press releases available in the database (let’s call this template listpress.php) and the other template will display individual press releases (let’s call this one displaypress. php). You can design the look and feel for these pages using your favorite HTML editor. Just remember to leave an area where the dynamic content (which will, of course, be of variable length) can be inserted. Once you’ve designed a nice looking HTML page, just drop in the PHP code to query and retrieve the data from the database. When either page is called by the Web server, the Web server will process the PHP code and replace it with dynamic content from the database.

The last thing you will need to do is copy these new template files to one of your Web server directories. Two important items to remember: One, the template file you create must have a name that ends in .php. Two, the template files must have the execute permission bit set (type chmod +xfilename). And that’s it!

Adding Functionality

It’s easy to add a ton of functionality to our press release engine. We may want to sort the links of available press releases by date or by title, but group them by year. Or perhaps you want to display a random press release on your home page to keep it fresh. The exciting part is that we can copy our listpress.php page and experiment with it to our heart’s content, knowing that all the data is safely tucked away in our database. Probably the most useful feature we could add would be a Web form to enter new press releases into our database.

For more information on how to extend the functionality of a dynamic Web site, and for some great examples, Professional PHP Programming from Wrox Press is an indispensable book.

Summary of Benefits

Hopefully this article has helped to convince you that dynamic Web pages aren’t as difficult to create as you may have thought and that they can be of tremendous benefit to your Website. They reduce your maintenance and administration, help distribute your workload, increase your responsiveness, and allow you to get lots of content up quickly. Also, the combination of Apache, PHP and MySQL provide an easy to use, cross platform, and scalable development environment. Have fun!

Creating a Simple Database Using MySQL

Planning the Database

The first and most important step when creating a database is to plan your design. Remember to think about future needs. It is often better to have unused fields in your database than to have to add them later.

Step 1

We need to name the database. Let’s call ours Websitedb.

Step 2

We need to define what tables our database will hold. A database can contain hundreds of tables. Initially we will only need one table to hold our press releases, but we might want to add other tables later. We will call our initial table newsItems.

Step 3

We need to define the fields that our table will contain. These fields will represent all of the elements of a press release. Our example will have five fields — title, date the press release was made available, name of the person who entered the press release, actual press release copy, and an ID field. The ID field is a unique identifier by which we will be able to track each press release. We’ll cleverly name these fields title, datePosted, author, body, and id.

Creating the Database

Figure 2-MySQL CommandLine
Figure Two: Connecting to MySQL through the command line.

Now we need to connect to MySQL and create our database. The following example demonstrates how to do this from the command prompt in order to illustrate the inner workings of MySQL, however there are several GUI tools available to make this job easier. (See Figure One, pg. 65.)

To avoid discussing setting up accounts and permissions for MySQL, we will assume that you are logged in as root. Also, since each command below could easily be an entire article itself, we can’t really get into any syntax specifics. If you want more info about the commands, refer to the MySQL documentation (it came free with the software). Figure Two illustrates how the following will look on screen.

Step 1

Bring up a terminal window (if you are running X) and connect to MySQL by entering mysql at the command prompt. You should get a mysql> prompt.

Step 2

Enter: CREATE DATABASE Websitedb; (This application allows you to enter multiple line commands, so the semi-colon at the end is very important. It signifies the end of the command.)

Step 3

Enter: USE Websitedb;

Step 4

body TEXT, datePosted DATE);

Step 5

Now that we have created a table to hold our data, we need to populate it with some sample data. So, at the mysql> prompt, enter the text you see in Figure Three. Note that we didn’t specify an id number. This is because the id automatically increases incrementally. Please also note the syntax for the date. It is entered year/ month/day.

INSERT INTO newsitems (title, author, body, datePosted)
VALUES (‘My First Dynamic Article’, ‘Larry Roth’,'This is my first
dynamic article, using MySQL and PHP.’, ’2000/5/1′);

Figure Three

Go ahead and enter some more values into the database using the INSERT command. To view what had been entered, type SELECT*FROM newsitems at the mysql> prompt.

Creating Dynamic Web Pages Using PHP

Listing the Articles

Once you have a database up and running (See the Creating a Simple Database using MySQL sidebar, pg. 68), it is very easy to get it connected to a Web page. We will start by creating a simple Web page that displays all the press releases we have in our database. Note: By default, Apache should be using the /home/httpd/html directory as the root of your Web server, so that is where we should create these Web pages.

Step 1

Using your favorite text editor, create the file in Figure Four.

<!– PHP Part I Code To Go Here –>

<title>Press Releases 2000</title>
<body bgcolor=”#ffffff”><h2>Press Releases</h2>

<!– PHP Part II Code To Go Here –>


Figure Four

Step 2

Add the PHP code in Figure Five (PHP Part I) to open and query the database. Note that PHP uses a <?php start tag and a ?> end tag. Everything between these tags is expected to be PHP code.

$sql = “SELECT * FROM newsitems”;
$rs = mysql_db_query(“Websitedb”,$sql);

Figure Five

This bit of PHP code will go before the <html> tag (where you see the HTML comment <!– PHP Part I Code To Go Here –>). Let’s examine what it does.

The first line simply creates a variable ($sql) and sets it equal to a string (“SELECT * FROM newsitems”). This string queries the database. The second line is a function to connect us to the MySQL engine. The last line creates a recordset. A recordset contains the results of a query. In this case it will hold the name of our database and the results of our query. The recordset is stored in the variable $rs.

Step 3

Add the code in Figure Six (PHP Part II) to loop through each press release and display the titles:

//This loop iterates through all the recordsets.
while ($row = mysql_fetch_object($rs)) {
$id = $row->id;
$title = $row->title;
printf(“<a href=\”displayarticle.php3?id=%s\”>%s</a><br>”,$id,$title);

Figure Six

This bit of PHP code in Figure Six will go after the <h2>PressReleases</h2> line (where you see the HTML comment <!– PHP Part II Code To Go Here –>). See Figure Seven for an example of how it all looks together.

Figure 3-Articles Listing
Figure Seven: PHP code to display all the press releases in our database.

So what have we coded? The first line is a comment line — a note to help anyone looking at this file determine what the code is about. The second line starts a loop. It will repeat all the code between the braces. In our case, this will be until we run out of rows to process in our table. Also, notice the mysql_fetch_object command on this line. This command gets a row of data from the recordset we created and stores it in the variable $row.

The third and fourth lines retrieve individual fields from the row and store them into variables. The fifth line should look very familiar to C programmers — it’s a print statement that creates the actual HTML code that gets sent to the browser. Notice that this line is displaying the title of our press release and it creates a link that passes the ID number of the press release along to the final Web page that will display it.

Step 4

We need to save the newly created page and set the permissions for it. Let’s call it listpress.php3, and save it to the /home/httpd/html folder.

If the permissions are not already set, you need to add read and execute permissions to the file. This is done by issuing the command chmod +rx listpress.php3.

Step 5

View our results! Bring up a browser and point it to http://localhost/listpress.php3 And you should see your articles/press releases listed as hyperlinks.

Don’t worry if you get an error message. Just double-check the file you created for typos. If you view the source code from your browser, you will notice that none of our PHP code is displayed. Since it is processed at the server, it is not passed through to the browser.

Displaying the Press Release

Figure 4-Display Listing
Figure Eight: PHP code to display an individual press release.

Now that we have a way to list all the press releases on a single page, let’s create another page that will display individual press releases. Create the file shown in Figure Eight. Call it displaypress. php3 and store it in the /home/httpd/html directory. Make sure you set the permissions as we did with the previous example.

Notice that our query string now has a WHERE clause. The .$id at the end of the string “SELECT*FROM newsitems WHERE id=”.$id; attaches the value of $id onto the string. One nice feature of PHP is that for any form data passed through a PHP page (in our case the value of the .$id variable), PHP will automatically create and set a variable for it. So now, the WHERE clause retrieves a specific row for us. We no longer have to loop through a recordset; we are just printing out the contents of that row.

There are an infinite number of ways upon which these examples can be expanded. The most obvious is to make a more attractive HTML page. The nice thing about PHP is that we can change the surrounding HTML code, and simply drop in the same PHP scripts. We may have to modify our printf statements slightly, but the bulk of what is there will still work, no matter what is wrapped around it.

Larry Roth is the CTO of Navistream Corporation. He can be reached at lroth@navistream.com.

Comments are closed.