Re: Checking for existance for data in a column
You can most likely preclude empty/invalid data with SQL. Let's say your field/column name is 'name'. Then with your DBI prepare() call, you can preclude records where name is blank, null, or whatever you'd like. $sth = $dbh-prepare( 'SELECT * FROM table WHERE name IS NOT NULL' ); $sth-execute; # Proceed with your fetchrow_hashref()'s, etc HTH Have Fun! Jason T. Murlidharan Nair [EMAIL PROTECTED] wrote in message [EMAIL PROTECTED]">news:[EMAIL PROTECTED]... Hi!! I have a CGI that looks up data from a mysql data base and does a bunch of calculations. I only want to do calculations on the columns which contains any data. What I mean is for some colums there is no data available at all. So I don't want to do any calculations on them obviously. How do I check whether the column contains data, once I have retrived all the data using fetchrow_hashref(). Thanks and Cheers alway!! Murli -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: multiple selection
Two things: 1) Your action parameter of the form tag was pointing to a separate program. If you leave it blank (or leave it out altogether), then this same script will process it. 2) You don't need to split param('list') - CGI.pm will automatically make an array for you, if it contains multiple entries. HTH Have Fun! Jason #!/usr/local/bin/perl use CGI qw(:standard); $action = param('action'); print header(); print start_html(); if (!$action) { print start_html(); print qq~ form method=POST action= input type=hidden name=action value=doit font face=arial size=2BSelect List:/BP ~; print scrolling_list( -name='list', -value=['List_1','List_2','List_3'], -default=['List_1'], -multiple=1 ); print qq~ input type=submit value=Submit/form ~; print end_html(); } else { @lists = param('list'); print qq|Total: @lists|; } exit(); Mikeblezien [EMAIL PROTECTED] wrote in message [EMAIL PROTECTED]">news:[EMAIL PROTECTED]... Hello all, having a problem with processing multiple selection from a scrolling list... first time working with tha scrolling list. Here is the test script I'm working with: #!/usr/local/bin/perl use CGI qw(:standard); $action = param('action'); print header(); print start_html(); if (!$action) { print start_html(); print qq~ form method=POST action=/mailer/cgi/list.pl input type=hidden name=action value=doit font face=arial size=2BSelect List:/BP ~; print scrolling_list(-name='list', -value=['List_1','List_2','List_3'], -default=['List_1'], -multiple=1); print qq~ input type=submit value=Submit/form ~; print end_html(); } else { @lists = split(/ /,param('list')); print qq|Total: @lists|; } exit(); Now I thought that the @list array would store all the selected values from the list... but it doesn't, just one, even if all the items have been selected from the list... what am I missing here ?? thanks -- MikemickaloBlezien =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Thunder Rain Internet Publishing Providing Internet Solutions that work! http://www.thunder-rain.com Tel: 1(985)902-8484 MSN: [EMAIL PROTECTED] =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: arrays lists
I know I am missing a lot in my knowledge, but I'm trying to figure something out seemingly am in a hole... MySQL can do a lot of this for you, I believe... You want a random record from the database and retrieve a particular field from that record: # Untested, but you would call this subroutine like so: # getRandomRecord( $dbh, SELECT field_Im_interested_in FROM $TABLE # WHERE month like $month and day like $day ); # NOTE: $sql (2nd parameter) can't already have a LIMIT in it, or any SQL # statement which a LIMIT suffix would result in an invalid SQL statement. sub getRandomRecord { my( $dbh, $sql ) = @_; my ( $sth, $randomNumber, $myValue ); $sth = $dbh-prepare( $sql ); $sth-execute; $randomNumber = int(rand( $sth-rows ) ); $sth-finish; # $randomNumber will be 0 = $randomNumber $sth-rows, which # fits nicely with MySQL's LIMIT clause ( $myValue ) = $dbh-selectrow_array( $sql . LIMIT $randomNumber, 1 ); return $myValue; } HTH Have Fun! Jason the task is as follows: 1) query a mysql database for as many records as match a criteria (I can do this OK) 2) put the resulting records, how ever many there are, into a list or an array 3) count the number of records I have retrived (I can do this OK) 4) choose a random record number (I can do this) 5) get the record corresponding to the random record number from the array 6) get a particular field from the stored record I am using DBI to get the data from the database. here is what I have so far: sub getRandomRecord{ my $cgi = shift; my $dbh = shift; my $month = shift; my $day = shift; my $searchResult; my $returnValue; #prepare and execute SQL statement $sqlstatement = SELECT * FROM $TABLE WHERE month like $month and day like $day; $sth = executeSQLStatement($sqlstatement, $dbh); $counter = 0; # put the records returned in an array/list count how many while ($searchResult = $sth-fetchrow_array() ) { # get the 4th field from the record in the array put it in the list my @list = ($searchResult[3]); ++$counter; } # pass the counter to the random integer routine get a value back my $randomNumber = getRandomNumber($counter); $returnValue = @list[$randomNumber]; # clean up the DBI $sth-finish(); return $returnValue } -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: listing perl modues on system
One easy way is to run the command: perldoc perllocal Jason Jerry M . Howell II [EMAIL PROTECTED] wrote in message [EMAIL PROTECTED]">news:[EMAIL PROTECTED]... Hello there, I was wondering if there is an easy way to list the perl modules that are installed on a system? -- Jerry M. Howell II -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: console window
At the end of your perl program, add the line: system( PAUSE ); http://www.computing.net/programming/wwwboard/forum/3270.html HTH, Jason Gary Rocco [EMAIL PROTECTED] wrote in message 001301c290f9$02bad3d0$93b500c7@hppavilion">news:001301c290f9$02bad3d0$93b500c7@hppavilion... when i ran perl programs using windows 98 operating system, i double clicked on the program name in windows explorer. i kept the program files right in the C:\Perl directory. the programs would open a command prompt type console window and execute. the console window remained open until i clicked on the X to close it. now i have a new hp pavilion pc running windows xp. everything else being the same, when i run the perl programs from windows explorer, the console window opens, executes and closes before i can see anything in it. i realize that if i open the command prompt, i can see the program results but i would like to be able to run the programs directly from windows. i have tried changing the suffix from .pl to .bat(using pl2.bat). the results are the same either way. thank you gary rocco [EMAIL PROTECTED] -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: Perl Editors
I like ActiveState's Komodo product. It's free for non-commercial use (tinkering at home, etc) and has a lot of great features, including a built-in debugger. Have fun! Jason Dale Pellerin [EMAIL PROTECTED] wrote in message [EMAIL PROTECTED]">news:[EMAIL PROTECTED]... Anyone have any suggestions for a Windows based perl editor with compiling functionality? Dale -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
How to profile CGI scripts?
Disclaimer: I've read the docs, talked to several folks, and played around with the scripts, but I must be missing something. I'd like to get the tmon.out file output from the -d:DProf flag when my CGI scripts execute remotely on the web server that I'm developing on, but whenever I add the '-d:DProf' flag in the shebang line, I get a 500 Internal Server Error. I've also tried setting the 'PERL_DPROF_OUT_FILE_NAME' environment variable in a BEGIN block. Any thoughts? Thanks in advance, Jason -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: How to profile CGI scripts?
I just tested a command line script by putting -d:Dprof in the shebang line and didn't have any problem. Of course, I'm using ActiveState here and that might make a difference. Perhaps you could tell us what's in your error log? Yea ... that's another problem - I don't have access to the error log - talk about your pure black box development. ;) The server I use is hosted by ValueWeb and it's a Linux box (I also believe it's an Apache server). The server I'm developing on is also Apache, but Win2K and ActiveState. The -d:DProf flag works fine on my box, though it's not using my $ENV{PERL_DPROF_OUT_FILE_NAME} definition. You could create a new file extension and associate that with the -d:Dprof flag. Then, run the script (with the new extension) and manually grab the tmon.out file. You could even write another perl script that runs continually in the background and detects the creation of the tmon.out file, grabs it, and writes it to a new directory with some sort of identifier embedded in the filename. Not following you here. The presence of -d:DProf seems to result in a 500 error for any script on the host I'm using, even a simple Hello World script. Jason -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: e-mailing HTML form results
I had this earlier this morning - this means the Net::SMTP object wasn't created. In my code, I redirected STDERR and created the object using Debug=1 to get more information. open (STDERR, /logs/mail_log); $msHandle = Net::SMTP-new ('localhost', Hello = '64.70.149.84', Timeout = 10, Debug = 1); ... Then you can check out the log to see what's going on. More than likely, the server you're trying to use is denying your request. To keep your code from 'dying', surround the rest of your code with an if clause: if ($msHandle) { # do the rest of the processing } Jason - Original Message - From: Helen Dickey [EMAIL PROTECTED] To: [EMAIL PROTECTED] Sent: Wednesday, July 25, 2001 4:14 PM Subject: re: e-mailing HTML form results Now I am getting the error message Can't call method recipient on an undefined value at feedback1SMTP.pl line 77. Does this mean that my address as recipient is wrong? Helen -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
Re: Needing a script to...
I'm working with Excel (just for the reading aspect, though) fortunately, someone has written ParseExcel ( WriteExcel). Looking on CPAN, I don't see a similiar offering for Word. The ParseExcel module does rely on the OLE::Storage_Lite module - you may want to check that out and see if that can help. In OLE::Storage, there's an example (lhalw) that draws text out of Word files. Can't do it with PDF or HTML files? (take the same information and put it in a PDF or HTML file and e-mail that doc format) Jason - Original Message - From: Susan [EMAIL PROTECTED] To: [EMAIL PROTECTED] Sent: Tuesday, July 17, 2001 1:57 PM Subject: Needing a script to... Does anyone know of a cgi or perl script that will work for taking the information from an online form, inputting the data onto a form on a word doc and then having that word doc form emailed to the email address? I know this can be done though I can not quite work myself through this one. Thanks for any info... -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
cookie/state challenge
In processing an HTML form, I need to get a userID field from a cookie from the client's browser. The cookie is created at the front-door of the site where the user can login. But the user could come directly to this HTML form, bypassing the login. So I see situations where the cookie doesn't exist. My question is when I process the form and the cookie doesn't exist, how can I get the user to login (or register) and afterwards, continue to process the original HTML form. I thought of having my script create a dynamic form with hidden fields, going to a separate script to handle login/registration and setting up the cookie and then possibly handing the hidden field information back to the original script to process, but that seems messy (or at least I've got a hunch that there's a better way). I don't know much about the production environment (I just have FTP access), but I do know it doesn't support mod_perl. Thanks in advance! Jason
Re: test script
Gotta know a few things ahead of time: what kind of server (Windows or UNIX) and the location of the perl interpreter. Making some gross assumptions, try: #!/usr/local/bin/perl -w print Content-type: text/html\n\n; print Hello World!BR\n; --- Next, see if the server has CGI installed: #!/usr/local/bin/perl -w use CGI; use strict; my $htmlPage = new CGI; print $htmlPage-header; print Hello World!BR\n; Place the script in a cgi-bin directory (upload using ASCII format), give it the right permissions (rwxr-x-r-x), make sure it ends in .pl (or .cgi) and then in your Web browser, go to that URL. These are also making more assumptions, but give it a shot and let us know what does or doesn't work if you have further complications. Jason - Original Message - From: john.twycross [EMAIL PROTECTED] To: [EMAIL PROTECTED] Sent: Wednesday, July 11, 2001 10:25 AM Subject: test script Can anyone tell me what is the most basic script that I can load onto a server to test that it is working? Thanks John Twycross
Re: Sources
My guess would be permissions and how you have your mysql server setup. When you're running the script on the terminal, it's using your ID to connect to the database server. When the webserver's running the script, it's using the server process' ID. I'm not sure if that's the right answer, though - GURUs: do databases answer anonymous requests provide the names of the available sources, no matter who's requesting it? Jason - Original Message - From: Guillaume Denizot [EMAIL PROTECTED] To: [EMAIL PROTECTED] Sent: Tuesday, July 10, 2001 4:45 AM Subject: Sources Hello, when I execute this script : #!/usr/bin/perl -w use DBI; print Content-type:Text/html\n\n; print bPilotes disponibles:/bbr\n; @drivers=DBI-available_drivers; foreach(@drivers) { print $_ br\n; } $driver=mysql; @sources=DBI-data_sources($driver); print \nbrbSources de donnees disponibles:/bbr\n; foreach(@sources) { print $_ \nbr; } with the terminal, I obtain: Pilotes disponibles: ADO ExampleP Multiplex Proxy mysql Sources de donnees disponibles: DBI:mysql:mysql DBI:mysql:test but when this script is called in HTML page like form action=/cgi-bin/my_script.pl method=POST I obtain only: Pilotes disponibles: ADO ExampleP Multiplex Proxy mysql Sources de donnees disponibles: Why not sources of mysql driver? Thanks... _ Le journal des abonnés Caramail - http://www.carazine.com
Re: Errors
Got 2 3 covered - rwxr-xr-x and /usr/local/bin/perl'd the scripts (that's one annoying thing I have to update whenever I upload code from my Win32 machine to their Linux box). #1 - tried that and still getting the ISE, so it must be a compiler error ... I didn't know all of those tips - that will help me with this problem (and w/ future ones, too) - now if I could just find out what the compiler problem is ... the syntax checks out ... I can't telnet execute the script in their environment. So you can't just have the normal STDERR that goes to the error_log redirected to a file of your choice? Jason - Original Message - From: Curtis Poe [EMAIL PROTECTED] To: CGI Beginners [EMAIL PROTECTED] Sent: Tuesday, July 10, 2001 1:13 PM Subject: Re: Errors --- Jason Purdy [EMAIL PROTECTED] wrote: I'm working on a web site that's hosted by ValueWeb (not important, but they give you CGI access but they don't give you access to the error log). So I feel like I'm flying (coding) blind sometimes. Especially when I get the Internal Server Error. The scripts in question are inherited code and a bit complicated, so it would be MUCH better to see what's going on instead of commenting in/out code to track down the problem. I've tried: BEGIN { open (STDERR, /path/to/error_log);# also tried /path/to/error_log *shrug* ;) } Also added on (thought maybe the output wasn't flushing or something like that): END { close (STDERR); } And that creates a 0-byte file that doesn't have any contents. My question is: How can I track down what's going on, on this remote server (with it's own unique setup/environment [it works great on my computer])? Thanks in advance! Jason Here are a couple of things you can check: 1. Top of script: use CGI::Carp qw/fatalsToBrowser/; $|++; That should route many error messages directly from the error log to the browser. If that doesn't work, it may mean that your script is not compiling. The second, cryptic, command will disable output buffering which should increase the likelyhood of getting *some* output to the browser, so long as your script is compiling. 2. Are your permissions set correctly? 3. Does your shebang line point to the Perl interpreter? Cheers, Curtis Poe = Senior Programmer Onsite! Technology (http://www.onsitetech.com/) Ovid on http://www.perlmonks.org/ __ Do You Yahoo!? Get personalized email addresses from Yahoo! Mail http://personal.mail.yahoo.com/
Re: By popular request: the source of the invisible webscript.
Well, the slashes (\\) are the wrong way ... try this: print HTML\nHEAD\nTITLETest Script/TITLE\n/HEAD\nBODY\nTest.\n/BODY\n/HTML; Netscape is more strict than IE w/ HTML, so if you were using Netscape, this could be your problem. Jason - Original Message - From: Samuel Brown [EMAIL PROTECTED] To: [EMAIL PROTECTED] Sent: Tuesday, July 10, 2001 1:59 PM Subject: By popular request: the source of the invisible webscript. Here's the script who's output I've described as not being displayed in the browser window, even tho 'View Source' shows it as correctly transmitted. print Content-Type: text/html\n\n; # HTML header, normally supplied automatically # by the server for HTML files. print HTML\nHEAD\nTITLETest Script\\TITLE\n\\HEAD\nBODY\nTest.\n\\BODY\n\\HTML; S. __ Do You Yahoo!? Get personalized email addresses from Yahoo! Mail http://personal.mail.yahoo.com/
Re: newbie question
I'm not familiar with WinCGI, but your code is missing the important shebang line. I have Apache running on my Windoze box and my shebang is: #!\Perl\bin\perl Everything's off my C drive and the DOS path to Perl is: C:\Perl\bin\perl. Jason - Original Message - From: nila devaraj [EMAIL PROTECTED] To: Aaron Craig [EMAIL PROTECTED] Cc: [EMAIL PROTECTED] Sent: Monday, July 09, 2001 12:29 AM Subject: Re: newbie question Hi Thank you for your mail. the code is #testcgi.cgi print Content-type: text/html\n\n; print Hello World\n; This is WinCGI. should i have to give the Shebang operator? Should i have Perl installed in the server where the Webserver is configured? If so, how will i give the shebang operator The web server is Iplannet webserver. It would be appreciated if anyone help me to come out of this problem Thank you Regards Nila __ Do You Yahoo!? Get personalized email addresses from Yahoo! Mail http://personal.mail.yahoo.com/
Re: Required Fields Module
I posted the original message, but my code is not an alternative to CGI - it's a supplement to validate a form-fed CGI script and that certain elements were filled out by the user. It requires CGI, actually. Found a link that described how to do this on the JavaScript side: http://www.webdeveloper.com/javascript/js_form_example.html Jason Code (assumes you already printed the HTML header and takes in two arguments: the CGI object and a hash table of required fields): sub checkRequiredFields { my ($formHandle, %reqdFields) = @_; my ($incomplete) = 0; my (@incFields) = (); foreach $field (keys %reqdFields) { if ($field =~ /(.*)\|\|(.*)/) { $incomplete = 1 push (@incFields, $reqdFields{$field}) if ( (!grep(/$1\b/, $formHandle-param) || $formHandle-param($1) eq '') (!grep(/$2\b/, $formHandle-param) || $formHandle-param($2) eq '') ); } else { $incomplete = 1 push (@incFields, $reqdFields{$field}) if !grep(/$field\b/, $formHandle-param) || $formHandle-param($field) eq ''; } } if ($incomplete) { print H2Incomplete Form/H2\n; print You missed the required fields:BR\nUL\n; foreach $incField (@incFields) { print LI$incField\n; } print /UL\n; print CENTERIUse your browser's back button try again/I/CENTER\n; exit; # I couldn't just use the die, b/c it wouldn't format the $msg like I wanted } } -- Example Hash: %requiredFields = ( 'upload_file' = 'Document Source', 'doc_url||docfile' = 'Specify either Document URL or Document File', 'capture_date' = 'Capture Date', 'contributor_type' = 'Contributor Type' ); - Original Message - From: Curtis Poe [EMAIL PROTECTED] To: CGI Beginners [EMAIL PROTECTED] Sent: Monday, July 09, 2001 12:41 PM Subject: Re: Required Fields Module --- fliptop [EMAIL PROTECTED] wrote: since I don't use CGI.pm for basic web stuff, I have my own function getting values out of the query string, and it was only giving me the last value of MultipleSelectMenu -- bad :( that's why you'll be better off just always using CGI.pm or some other modern equivalent. I don't agree. Why should I spend all that time loading up CGI.pm when all I want to get is the query string? It's far more efficient to have a subroutine that does that. If I want to use CGI.pm's many features, such as form writing, or file uploading, or whatever, it's worth loading the module up. But for simple, one-time things like getting user input, I think it's overkill to use CGI.pm. Gah!!! I wish I had seen this thread sooner (I've been out with the flu). Whoever wrote their own alternative to CGI.pm, post your code and I'll point out plenty of flaws in it. I'm sure I'll find at least 5 (one of these days I'll find fewer in a hand-rolled version, but I haven't yet). I'm not saying this to be rude, but CGI tends to be much trickier than people think even though it looks really simple. If you plan to do any long-term work with CGI, why not go with the industry standard? It's the standard because it works. Oh, and about the overhead of loading CGI.pm: if you have a site that is so slow that loading CGI.pm is causing performance issues, than CGI.pm is the last of your worries. If you are worried that you'll get to the point where CGI.pm will cause those performance issues, than your hand-rolled version will not be adequate. At the very least, check out CGI::Lite. Cheers, Curtis Poe = Senior Programmer Onsite! Technology (http://www.onsitetech.com/) Ovid on http://www.perlmonks.org/ __ Do You Yahoo!? Get personalized email addresses from Yahoo! Mail http://personal.mail.yahoo.com/
Re: how to upload a file through an html form?
One thing that snagged me with printing to a filehandle is the binmode. I was uploading an Excel spreadsheet and writing it, but it would become corrupted (b/c it's a binary file). So if you're dealing with binary files (and according to the docs, if your system knows the difference [which for me, I saw on Win2K and Linux]), do a binmode before you print to the filehandle. ie: open (OUTFILE, /path/to/file); while ($bytesread=read($batchUpload, $buffer, 1024)) { binmode STDOUT; # is this necessary? binmode OUTFILE; print OUTFILE $buffer; } close (OUTFILE); Jason - Original Message - From: Curtis Poe [EMAIL PROTECTED] To: CGI Beginners [EMAIL PROTECTED] Sent: Monday, July 09, 2001 12:51 PM Subject: Re: how to upload a file through an html form? --- fliptop [EMAIL PROTECTED] wrote: Not true. Printing the file contents directly to the screen is a common method of testing whether or not the file upload was successful and has nothing to do with whether or not Hytham was properly uploading the file. yes, but the original poster was confused as to why when he searched the hard drive he couldn't find the file. Sigh. I need to read these darned things closer :) Cheers, Curtis Poe = Senior Programmer Onsite! Technology (http://www.onsitetech.com/) Ovid on http://www.perlmonks.org/ __ Do You Yahoo!? Get personalized email addresses from Yahoo! Mail http://personal.mail.yahoo.com/
Re: how to upload a file through an html form, again.
Check out the CGI documentation - it's very thorough and has a lot of excellent examples. Looking at the synopsis example, it looks like you're missing an if ($q-param()) { ... } around the file uploading part of your code. Give that a shot... Jason here it is: #!/usr/bin/perl use CGI; $q = new CGI; print $q-header, $q-start_html('title here'), $q-h1('Please fill this form'), $q-start_multipart_form, $q-filefield(-name='uploaded_file', -size=50, -maxlength=80), $q-submit, $q-end_form, $q-hr; if ($q-param()) { $file=$q-upload('uploaded_file'); if (!$file $q-cgi_error) print $q-header(-status=$q-cgi_error); exit 0; } open(FILE, /home/eHytham/public_html/upload.it); while($bytesread=read($file,$buffer,1024)){ binmode STDOUT; binmode FILE; print FILE $buffer; } close(FILE); }
Re: Required Fields Module
Excellent points - Thanks for pointing them out! I'll check out your tutorial soon (took a quick glance earlier this afternoon and it looks very thorough, and a good read! Thanks! :)). I forgot the print $query-header part of the code. I also updated the code to accept '0' values by grepping within the keywords. I currently don't have to worry about multivalued parameters - I don't design my forms that way. Jason New subroutine: sub checkRequiredFields { my ($formHandle, %reqdFields) = @_; my ($incomplete) = 0; my (@incFields) = (); foreach $field (keys %reqdFields) { if ($field =~ /(.*)\|\|(.*)/) { $incomplete = 1 push (@incFields, $reqdFields{$field}) if ( (!grep(/$1\b/, $formHandle-keywords) || $formHandle-param($1) eq '') (!grep(/$2\b/, $formHandle-keywords) || $formHandle-param($2) eq '') ); } else { $incomplete = 1 push (@incFields, $reqdFields{$field}) if !grep(/$field\b/, $formHandle-keywords) || $formHandle-param($field) eq ''; } } if ($incomplete) { print H2Incomplete Form/H2\n; print You missed the required fields:BR\nUL\n; foreach $incField (@incFields) { print LI$incField\n; } print /UL\n; print CENTERIUse your browser's back button try again/I/CENTER\n; exit; # I couldn't just use the die, b/c it wouldn't format the $msg like I wanted } } - Original Message - From: fliptop [EMAIL PROTECTED] To: Jason Purdy [EMAIL PROTECTED] Cc: [EMAIL PROTECTED] Sent: Sunday, July 08, 2001 1:38 PM Subject: Re: Required Fields Module [snip] hi jason after looking at your code, and not typing it in and trying it out, here are some of the problems i see with it: problem: what if a user passes a value of 0 in one of the required fields? let's say one of your required fields is 'number_of_kids'. some people may not have any, and therefore may enter '0'. your code checks to see if a required field is true/false. your code will not accept a value of 0 (it will think it's false, even though it's a valid answer). instead of checking to see if a field is true/false, check to see if it's defined, then check to see if it contains a minimum number of characters. problem: if there is an error, you're not sending the appropriate header command. if you just try to print HTML without calling $query-header, the result will be an internal server error. problem: what if your parameters are multivalued? assume for the moment your cgi is called like this: /cgi-bin/whatever.cgi?name=fliptoplang=perllang=english will your code handle these values the way you want? here are my recommendations: 1) put the parameters you're looking for into a list like this: (key1, value1, key2, value2, key2, value3, ...) 2) create a parameter hash from this list with values being either scalar or references to arrays: %parameters = ( key1 = value1, key2 = [ value2, value3] ); 3) check each key's value(s) (if it's required, ie.- not NULL) to see that they're defined and have a minimum length. if you haven't already seen it, i'd recommend reading the tutorial i'm working on which explains how to do all of these things. it can be found at http://www.peacecomputers.com/addressbook_toot-intro.html.
Re: Required Fields Module
Oops - found another little tweak - it should be $formHandle-param instead of $formHandle-keywords (unless your form is using an ISINDEX search). Sorry 'bout that... Jason - Original Message - From: Jason Purdy [EMAIL PROTECTED] To: [EMAIL PROTECTED] Cc: [EMAIL PROTECTED] Sent: Sunday, July 08, 2001 11:14 PM Subject: Re: Required Fields Module Excellent points - Thanks for pointing them out! I'll check out your tutorial soon (took a quick glance earlier this afternoon and it looks very thorough, and a good read! Thanks! :)). I forgot the print $query-header part of the code. I also updated the code to accept '0' values by grepping within the keywords. I currently don't have to worry about multivalued parameters - I don't design my forms that way. Jason New subroutine: sub checkRequiredFields { my ($formHandle, %reqdFields) = @_; my ($incomplete) = 0; my (@incFields) = (); foreach $field (keys %reqdFields) { if ($field =~ /(.*)\|\|(.*)/) { $incomplete = 1 push (@incFields, $reqdFields{$field}) if ( (!grep(/$1\b/, $formHandle-keywords) || $formHandle-param($1) eq '') (!grep(/$2\b/, $formHandle-keywords) || $formHandle-param($2) eq '') ); } else { $incomplete = 1 push (@incFields, $reqdFields{$field}) if !grep(/$field\b/, $formHandle-keywords) || $formHandle-param($field) eq ''; } } if ($incomplete) { print H2Incomplete Form/H2\n; print You missed the required fields:BR\nUL\n; foreach $incField (@incFields) { print LI$incField\n; } print /UL\n; print CENTERIUse your browser's back button try again/I/CENTER\n; exit; # I couldn't just use the die, b/c it wouldn't format the $msg like I wanted } } - Original Message - From: fliptop [EMAIL PROTECTED] To: Jason Purdy [EMAIL PROTECTED] Cc: [EMAIL PROTECTED] Sent: Sunday, July 08, 2001 1:38 PM Subject: Re: Required Fields Module [snip] hi jason after looking at your code, and not typing it in and trying it out, here are some of the problems i see with it: problem: what if a user passes a value of 0 in one of the required fields? let's say one of your required fields is 'number_of_kids'. some people may not have any, and therefore may enter '0'. your code checks to see if a required field is true/false. your code will not accept a value of 0 (it will think it's false, even though it's a valid answer). instead of checking to see if a field is true/false, check to see if it's defined, then check to see if it contains a minimum number of characters. problem: if there is an error, you're not sending the appropriate header command. if you just try to print HTML without calling $query-header, the result will be an internal server error. problem: what if your parameters are multivalued? assume for the moment your cgi is called like this: /cgi-bin/whatever.cgi?name=fliptoplang=perllang=english will your code handle these values the way you want? here are my recommendations: 1) put the parameters you're looking for into a list like this: (key1, value1, key2, value2, key2, value3, ...) 2) create a parameter hash from this list with values being either scalar or references to arrays: %parameters = ( key1 = value1, key2 = [ value2, value3] ); 3) check each key's value(s) (if it's required, ie.- not NULL) to see that they're defined and have a minimum length. if you haven't already seen it, i'd recommend reading the tutorial i'm working on which explains how to do all of these things. it can be found at http://www.peacecomputers.com/addressbook_toot-intro.html.
Required Fields Module
I wrote this simple lil' diddy as a reusable module to check required fields and wanted to share it. You can put this in a central .pl file to be required by any CGI script that needs to verify that certain fields have been filled out. Probably makes more sense to do this type of verification through JavaScript on the client-side, but I'm not as familiar with that. You just need to create a hash with left-values of the INPUT name from the form and right-values of a long-form/presentable form of the field. Then you can call this routine with 2 parameters - the CGI object [requires CGI] and the hash of your required fields. I also added support for a left value with ||'s - meaning if you have a situation (as I did) where one of two fields has to be required, but not both. You may also want to modify the code to format the output/behavior of the clause of when a form is incomplete. I am a sorta-newbie (experienced, but rusty), so I'm sure there are better ways to write the code or even if the code is written into some other module out there. HTH, Jason Example Hash: %requiredFields = ( 'upload_file' = 'Document Source', 'doc_url||docfile'= 'Specify either Document URL or Document File', 'capture_date' = 'Capture Date' ); Example Usage: #!/usr/local/bin/perl use CGI; require 'rfields.pl'; $query = new CGI; # let's start by checking the required fields checkRequiredFields($query, %requiredFields); ... Code: sub checkRequiredFields { my ($formHandle, %reqdFields) = @_; my ($incomplete) = 0; my (@incFields) = (); foreach $field (keys %reqdFields) { if ($field =~ /(.*)\|\|(.*)/) { $incomplete = 1 push (@incFields, $reqdFields{$field}) if ( (!$formHandle-param($1) || $formHandle-param($1) eq '') (!$formHandle-param($2) || $formHandle-param($2) eq '') ); } else { $incomplete = 1 push (@incFields, $reqdFields{$field}) if !$formHandle-param($field) || $formHandle-param($field) eq ''; } } if ($incomplete) { print H2Incomplete Form/H2\n; print You missed the required fields:BR\nUL\n; foreach $incField (@incFields) { print LI$incField\n; } print /UL\n; print CENTERIUse your browser's back button try again/I/CENTER\n; exit; # I couldn't just use the die, b/c it wouldn't format the $msg like I wanted } }