|
Description:
I developed this technique as an alternative to having to specifically cast name-value pairs into discrete Perl variables within your program.
This a technique where you capture all of an HTML form's data into a usable hash at one point in the program. Since the hash is a public variable, the form data is then available throughout your Perl script. Call this subroutine early in your script and the name-value pairs are magically available throughout the script without having to manually declare a Perl variable and get each and every value from the form's query string.
Not using a database but want to save the form ? Pipe the hash into an open DBM file...
Need to set the values of form fields ? You can assign to the $PARAMS hash $PARAMS{NEWVALUE} = "Cool trick.";
Need to do a database INSERT ? Embed the hash elements directly into your SQL construct and let $SQL->prepare($SQLSTMT) take care of it..
BTW: The $MSG variable is a little trick you can use to display what the form actually submitted to your Perl script... At any point / time in your program, AFTER getFormData() has been called, you can simply issue a
print "$MSG"; # FORM TRACE...
to see all of the form fields and the name value pairs that were submitted.
Usage: Text Source
Some simple examples:
if ($result = getFormData()) {
print "$MSG";
$COMPANY_NAME = $PARAMS{COMPANY_NAME};
$SQLSTMT = "INSERT INTO tblName (COMPANY_NAME) VALUES ('$PARAMS{COMPANY_NAME}')";
$SQL = $DBH->prepare("$SQLSTMT");
$result = $SQL->execute();
if($PARAMS{LOGIN_ID} eq "") {doLoginAgain();} else {doSomethingElse();}
} else {
die "Unable to retrieve form contents...";
}
sub getFormData() {
use CGI:
$capture = new CGI();
@FORMDATA = $capture->param();
%PARAMS = {};
foreach $line (@FORMDATA) {
chomp ($line);
$V = $capture->param($line);
chomp($V);
$line =~ uc($line);
$PARAMS{$line} = $V;
}
while (($key, $value) = each (%PARAMS)) {
$MSG .= "$key --> $value<BR>";
}
return TRUE;
}
The license for this recipe is available here.
Discussion:
If you are processing a LOT of forms in a web system (my systems generally consist of 130-140 discrete forms) you may want to use this technique to reduce the amount of code you actually need to write to retrieve the form contents (name-value pairs.).
I realized that processing form after form after form manually was extremely time consuming and prone to typographical errors, and that many times, I didn't even know which name-value pair was causing the error.
|