# Listing 2: search.pl
#!/usr/bin/perl -wT
# search.pl, which allows people to search through postings
use strict;
use diagnostics;
use CGI;
use CGI::Carp qw(fatalsToBrowser);
use DBI;
# This call to "use lib" should reflect the location of
# ATFConstants.pm, which defines $database, $server, $port, $username,
# and $password
use lib qw(/home/reuven/www/cgi-bin);
use ATFConstants;
my $message_id = "";
my $thread_id = "";
my $subject = "";
my $author = "";
my $thread_name = "";
# Remove buffering
$| = 1;
# ------------------------------------------------------------
# Create an instance of CGI
my $query = new CGI;
my $term = $query->param("term");
my $regexp = $query->param("regexp");
# Send a MIME header
print $query->header("text/html");
print $query->start_html(-title => "Search results",
-bgcolor => "#FFFFFF");
print "
Search results
\n";
# ------------------------------------------------------------
# Connect to the database
my $dbh =
DBI->connect("DBI:mysql:$database:$server:$port",$username,$password);
die "DBI error from connect: \"$DBI::errstr\"" unless $dbh;
# ------------------------------------------------------------
# Get information about the thread
my $sql = "SELECT M.id, M.thread, M.subject, M.author, T.subject ";
$sql .= "FROM ATFMessages M, ATFThreads T ";
# Should we treat this as a regular expression?
if ($regexp eq "yes")
{
$sql .= "WHERE M.text REGEXP \"$term\" ";
}
# Or should we treat this as a literal phrase?
else
{
# Remove SQL regexp characters
$term =~ s|%|\\\%|g;
$term =~ s|_|\\\_|g;
$sql .= "WHERE M.text LIKE \"%$term%\" ";
}
$sql .= "AND M.thread = T.id ";
$sql .= "ORDER BY M.date desc";
# Send the query
my $sth = $dbh->prepare($sql);
die "DBI error with prepare: \"$sth->errstr\"" unless $sth;
# Execute the query
$sth->execute;
die "DBI error with execute: \"$sth->errstr\"" unless $sth;
# We should only have received a single row. Print it out.
if ($sth->rows)
{
print "\n";
# Iterate through thread IDs and names
while (my @row = $sth->fetchrow)
{
($message_id, $thread_id, $subject, $author, $thread_name) = @row;
print "- $subject, ";
print "by $author in ";
print "";
print "$thread_name\n";
}
print "
\n";
}
else
{
print "No matches.
\n";
}
# ------------------------------------------------------------
# Menu bar
print "\n";
# Send the user to the posting form
print "[Post a message]";
print "\n";
# Send the user to the thread list
print "[View all threads]\n";
# Send the user to the search
print "[Search]\n";
# Allow the user to create a new thread
print "[Add a new thread]\n";
# Give a plug for the ATF home page
print "[ATF home]\n";
print "
\n";