A Sample CGI/DBI Program

In this section, we present—once again—a program that queries a MySQL database and prints results from the query. This time, however, we will format the results into a CGI page. Instead of generating HTML directly, like the $cgi->h2( ) call in the previous section, we’re going to separate the Model from the view in classic MVC fashion. We’ll use a popular Perl module called the Template Toolkit.

In this program, we store all the data we want to print in a set of Perl hashes. There is a headers hash used to generate the headers of a table (TH elements in HTML) and a records hash used to store information on each row retrieved from the database. We even use a hash element to store the title of the web page. This hash is the Model in our methodology, because it indicates the data and their relationships without making any presuppositions about how they are displayed.

Then we invoke the Perl Template module to turn our hash into HTML. The module uses our hash and a template we develop and store in a file called book_view.tt. Here’s the beginning of the file:

<html>
 <head>
     <title>[% title %]</title>
 </head>

It’s HTML, but has a placeholder for the title. We can therefore use the template over and over with pages that have different titles. There are placeholders for the other elements of our hash as well, and a lot of logic to do looping and other runtime choices. For instance, Example 9-4 shows a loop in the book_view.tt template file that causes odd-numbered ...

Get Managing & Using MySQL, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.