LJ Archive

Listing 2: The CGI version of our query program

#!/usr/bin/perl -w

use strict;
use diagnostics;
use Mysql;
use CGI;   # available from http://www.perl.com/CPAN

# Create an instance of CGI
my $query = new CGI;

# Send an appropriate MIME header
print $query->header("text/html");

# Begin the HTML output
print $query->start_html(-title =>
   "Query results");

# Connect via Unix sockets to the database on this
# server
my $dbh = Mysql->connect;

# Choose a database
$dbh->selectdb("test");

# Send our query
my $sth = $dbh->query(
   "select name,telephone from phone_book");

# Iterate through the returned rows
my @arr = ();

# Create a table for results
print "<table border=3>\n";

while (@arr = $sth->fetchrow)
{
    # Begin a new table row
    print "<tr>\n";

    # Print the first element in the first column
    print "<td>$arr[0]</td>\n";

    # Print the second element in the second
    # column
    print "<td>$arr[1]</td>\n";

    # End the row
    print "</tr>\n\n";
}

# End the table
print "</table>\n";

# End the HTML
print $query->end_html;

exit;
LJ Archive