Listing 3: Simple script to process queries and display results
#!perl
#!/usr/bin/perl

use CGI;
use DBI;
$q = new CGI;

$words = $q->param('search_words');
@words = split(/[^A-Za-z0-9]/,$words);
@letters = ("a","b","c","d","e","f","g");

# Display header
	&header;

# Connect
	$dbh = DBI->connect('DBI:mysql:lisa', "lisa", "lisa", {PrintError=>0,RaiseError=>0}) || die;

#Build the statement
	$statement = "SELECT DISTINCT url,title from doc \n"; 

# Add the join clauses
	$letter = 0;
	foreach $word(@words){
		$statement .= "inner join word as $letters[$letter] on doc.id=$letters[$letter].id \n";
		$letter++;
	}

# Add the where clause
	$statement .= "where title is not null and \n";
	$letter = 0;
	foreach $word(@words){
		$statement .= "$letters[$letter].word = '" . $word . "' and \n";
		$letter++;
	}

# Clean and terminate the statement
	$statement =~ s/and \n$/\n\;/;	

# Execute
	$sth = $dbh->prepare($statement) or print $DBI::errstr;
	$sth->execute() or print $DBI::errstr;

&display;
&footer;

#-----------------------------------------------------------------

sub display {

	print "<OL>\n";
	$results = 0;
	while (($url,$title) = $sth->fetchrow_array){
		$results = 1;
		if (length($title)<2){ $title = "No Title"; }
		print "<LI><A HREF=\"$url\">$title</A>\n";
	}
	print "</OL>\n";
	if ($results==0){ print "<P>We're sorry, but your search found no results at this time.\n";}
}

sub header {
	print "Content-type: text/html\n\n";
	print "<H1>Search Results</H1>\n";
	print "<P><I>Search: $words</I>\n";
}

sub footer {
	print "</BODY></HTML>";
}
