#!/usr/bin/perl -Tw # $Id: persons.cgi,v 1.9 1999-04-22 06:24:57 ivan Exp $ # Copyright (c) 1999 Ivan Kohler. All rights reserved. # This program is free software; you can redistribute it and/or modify it under # the same terms as perl itself use strict; use vars qw ( $data_source $user $password $table @fields $cgi $dbh ); use subs qw( print_form ); use CGI qw(tr th td); use CGI::Carp qw(fatalsToBrowser); use DBI; $data_source = "DBI:mysql:technostate"; $user = "agent"; $password = "t3chno"; $table = "PERSONS"; @fields = qw( PERSON_ID NAME EMAIL AFFILIATION HOMEPAGE ); $cgi = new CGI; $dbh = DBI->connect( $data_source, $user, $password ) or die "Cannot connect: ". $DBI::errstr; unless ( $cgi->param('magic') ) { #first time through my $sth = $dbh->prepare( "SELECT * FROM $table" ) or die $dbh->errstr; my $rv = $sth->execute; die $sth->errstr unless $rv; print $cgi->header( '-expires' => 'now' ), $cgi->start_html('Person listing'), $cgi->h1('Person listing'), ; unless ( $sth eq '0E0' ) { my @columns = @{ $sth->{'NAME'} }; print $cgi->start_table, $cgi->tr( map { $cgi->th($_) } @columns ) ; my %hash = (); my $hashref = undef; while ( $hashref = $sth->fetchrow_hashref ) { %hash = %{$hashref}; $hash{'EMAIL'} = ''. $hash{'EMAIL'}. ""; $hash{'HOMEPAGE'} = 'http://'. $hash{'HOMEPAGE'} unless $hash{'HOMEPAGE'} =~ /^http\:\/\//; $hash{'HOMEPAGE'} = ''. $hash{'HOMEPAGE'}. ""; print $cgi->tr( map { $cgi->td( $hash{$_} ) } @columns ); } print $cgi->end_table; } $cgi->param('magic', 'new_form'); print '
Add new person';
print $cgi->end_html;
exit;
} elsif ( $cgi->param('magic') eq 'new_form' ) {
$cgi->param('PERSON_ID', 0);
$cgi->param('magic', 'process_form');
&print_form( $cgi, "Add person" );
exit;
} elsif ( $cgi->param('magic') eq 'process_form' ) {
my $field;
foreach $field ( @fields ) {
if ( $cgi->param( $field ) ) {
$cgi->param( $field ) =~ /^(.*)$/;
my $param = $1 || 0;
if ( (DBI::looks_like_number($param))[0] ) {
$cgi->param( $field, $param );
} else {
$cgi->param( $field, $dbh->quote($param) );
}
}
}
my $statement = "INSERT INTO $table ( ".
join(', ', @fields ).
' ) VALUES ( '.
join( ', ', map { $cgi->param($_) } @fields ).
' )'
;
my $sth = $dbh->prepare($statement)
or die $dbh->errstr;
my $rv = $sth->execute;
die $sth->errstr unless $rv;
my $url = $cgi->url;
$url =~ s/^\/[\/]+$//;
print $cgi->redirect($url);
}
sub print_form {
my $cgi = shift;
my $action = shift;
print $cgi->header,
$cgi->start_html($action),
$cgi->h1($action),
$cgi->start_form,
$cgi->hidden( -name => 'PERSON_ID' ),
"Name: ", $cgi->textfield( -name => 'NAME' ), "
",
"Email: ", $cgi->textfield( -name => 'EMAIL' ), "
",
"Affiliation: ", $cgi->textfield( -name => 'AFFILIATION' ), "
",
"Homepage: ", $cgi->textfield( -name => 'HOMEPAGE' ), "
",
$cgi->hidden( -name => 'magic'),
$cgi->submit('Submit'),
$cgi->end_form,
$cgi->end_html;
;
}