#!/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
open (FORM, "../course/cgi_use/database_form.html")
	or die "Can't open database_form page: $!";

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

	print;

}

close FORM;