Previous Page Next Page

17.7. Using CGI and the DBI to Select and Display Entries

Once you have learned how to connect to a database and submit queries, you may want to use DBI in your CGI scripts to store and retrieve data for dynamic Web pages. In the first example, a simple CGI program demonstrates how to fetch data from the database and then format it as a table to be sent to the user's browser.

Example 17.45.

1 #!c:/ActivePerl/bin/perl.exe
2 use DBI;
3 use CGI qw(:standard);


4 my $dbh =
DBI->connect("DBI:mysql:host=localhost;database=sample_db;
    user=root;password=quigley1")or die "Connection to sample_db
failed:  $DBI::errstr";
;

5 my $sth=$dbh->prepare("SELECT * FROM coaches");
  $sth->execute();

6  print header, start_html(-title=>"Sample Database",
                         -BGCOLOR=>"#66ff33");
   print "<div align='center'>";
   print h2("Contents of the \"coaches\" Table");

7  print qq/<table border="1" cellpadding="10" bgcolor="white">/;
8  while(my @val = $sth->fetchrow_array()){
        print <<EOF;
         <tr>
              <td>$val[0]</td>
              <td>$val[1]</td>
              <td>$val[2]</td>
              <td>$val[3]</td>
              <td>$val[4]</td>
         </tr>
EOF
  }
   print "</table>";
   print end_html();
   $sth->finish();
   $dbh->disconnect();

					  

Explanation

  1. The shbang (pound sign, bang line) tells the Web server where Perl is installed so it can start up the Perl interpreter. This line is necessary for any operating system using the Apache server.

  2. We are going to be using the DBI module in this program to talk to the MySQL database.

  3. We will use the function-oriented version of the CGI module to use the standard CGI functions to talk to the Web browser.

  4. A connection is make to the MySQL database.

  5. A SQL SELECT statement is prepared. It will retrieve all of the records for the coaches table.

  6. The CGI header function sets the "Content-type: text/hmtl\n\n" line, and the HTML startup line to set a title and color for the HTML page. This information will be sent through the Common Gateway to the server and onto the browser.

  7. An HTML table is created to hold the data that will returned from the database.

  8. As the data is fetched from the database, it is formatted and sent back to the server, then presented as a table in the browser window.

The second example takes us full circle.

Figure 17.21. Client/server from browser to database.


CGI.pm creates a simple HTML form consisting of a text field. The user will select a team, type the team name into the form, and submit the form. The CGI program will process the form information, use the DBI module to connect to the MySQL database, retrieve the team's information, format it, and send it back to the browser as an HTML table.

Figure 17.22. DBI and CGI output.


Example 17.46.

1   #!c:/ActivePerl/bin/perl.exe

2   use DBI;
3   use CGI qw(:standard);

    print header, start_html(-title=>"Team Lookup",
                             -BGCOLOR=>"#66ff33"
                            );
4   print start_form,"<font face='arial' size='+1'>
    Look up what team? ",textfield('name'),p;
5   print submit, end_form, hr;

6   if(param())  {
7       $team = param('name');

8       $dbh =
        DBI->connect("DBI:mysql:host=localhost;database=sample_db;
        user=root;password=quigley1") or
        print "Connection failed: ". $DBI::errstr;
9       $sth=$dbh->prepare("SELECT name, wins, losses
                            FROM teams where name = ?"
                           );
        $sth->execute($team);
10      if ($sth->rows == 0){
            print "Your team isn't in the table.<br>";
            exit;
        }
        print h2("Data for \u$team");
        while(($name,$wins,$losses) = $sth->fetchrow_array()){
11          print <<EOF;
            <table border="1" bgcolor="yellow">
               <tr>
                   <th>Name</th>
                   <th>Wins</th>
                   <th>Losses</th>
               </tr>
               <tr>
                   <td>$name</td>
                   <td>$wins</td>
                   <td>$losses</td>
               </tr>
            </table>
12          EOF
            print end_html();
            $sth->finish();
            $dbh->disconnect();
        } # End while loop
    }  # End if block starting on line 6

					  

Explanation

  1. The shbang (pound sign, bang line) tells the Web server where Perl is installed so that it can start up the Perl interpreter. This line is necessary for any operating system using the Apache server.

  2. We are going to be using the DBI module in this program to talk to the MySQL database.

  3. We will use the function-oriented version of the CGI module to use the standard CGI functions to talk to the Web browser.

  4. This function starts an HTML form. This form is simple. It will consist of one HTML text field, where the user can enter data.

  5. The CGI submit function creates the form's Submit button. Once the user clicks the Submit button, the form will be submitted, and the data that was entered into the text field will be sent to the CGI Perl script for processing.

  6. Since the CGI module assigns this Perl script to the ACTION attribute in the HTML form, this Perl script will receive the form data and process it. The CGI module will check to see if there are any parameters, meaning, has the form returned any data? If the params function returns true, that means the form has been submitted and this part of the program will continue. If the params function returns false, then the form has not yet been submitted.

  7. The name of the text field in the HTML form was "name". The CGI params function takes the name of the text field as an argument and sends back the value that was assigned to it; in this case, the name of a team.

  8. We connect to the MySQL database to use the sample_db database.

  9. A SQL statement is prepared with a placeholder that will later be assigned the name of a team from the teams table.

  10. The query is executed and sent the name of the team the user selected when he filled out the form.

  11. After the result-set is returned from the database, a here doc is started. An HTML table is created within the here doc to present the result set, returned from the database, in a nice structured format on the browser. CGI will send this table to the Web server (Apache) and then on to the broswer (Firefox).

  12. This user-defined terminator marks the end of the here doc. Remember that this marker must be in the leftmost column of your Perl script and cannot have any trailing spaces; in fact, it must be terminated with a newline.

 

Figure 17.23. CGI, DBI, and a form.


Previous Page Next Page