Mike Gossland's Perl Tutorial Course for Windows


CGI In Use | Site Search | Presenting Data | Cookies


Chapter 7. CGI In Use

Presenting Data from a Database

Here's an example where a visitor can fill in a form and when form is submitted, the server stores the data in a database. The next time a visitor comes to the same page, the data that was uploaded by the previous visitor is now on display.

Here is a script that can do this:

  
#!/usr/bin/perl
#database_demo.pl

use CGI;
use CGI::Carp qw(fatalsToBrowser);

$cgi=new CGI();

chdir("cgi-bin");

#Print a new "Content type" header;
print $cgi->header();

#Get the fields from the form "col_1, col_2..."
#into the fields array
for $i ( 1 .. 5 ) {

	$fields[$i-1] = $cgi->param('col_'.$i);

}

#Check to make sure at least one field has an entry
if ( grep /\S/, @fields ) {

	#make the data comma separated
	$data_line = join ", ", @fields;

	#append the new data onto the old.
	#This is where you should use file
	#locking if you're worried about
	#multiple hits at the same millisecond
	open DATA, ">>database.txt"
		or die "Can't open database.txt";

	print DATA $data_line, "\n";

	close DATA;

}

#now reopen the whole data file for reading
open DATA, "database.txt"
	or die "Can't open database.txt";


while ( <DATA> ) {

	#turn comma separated values
	#into HTML table rows
	@fields = split /\s*,\s*/;

	$database_results .= "<tr><td>";
	$database_results .= join ( "</td><td>", @fields);
	$database_results .= "</td></tr>\n";
}

#substitute the results into the original form
$form = "long/long/path/to/form/on/server/.../database_form.html";
open (FORM, $form)
	or die "Can't open database_form page at $form: $!";

while ( <FORM> ) {
	
	#substitute the html into the reserved place	
	s{<!-- database_results -->}{$database_results};

	print;

}

close FORM;

  

Look through the code and read the comments for detailed explanations. In summary, the form input is parsed and saved onto the end of a "comma separated value" data file. Then the file contents are read back, turned into html table rows, and substituted into a placeholder in the original form.