...

View Full Version : Need Help with Perl Syntax PLEASEE



hackYourBrain
07-29-2009, 03:15 PM
Hi guys I have a lab to complete where I need to be able to access, pull and add data from a database. I wrote this scrip in perl but I dont know how to call functions using a button or an anchor tag for example. The mySQL statements work fine as I have tested them from command line. Can someone please tell me what the proper syntax is? as you can see I the only thing we have learned is how to use param(). Im refereing to the proper syntax in the startHtml() =>script and the buttons in the subHtmlForm().. I also dont know if its legal that im using cgi.pm and regular xhtml at the same time.. dont think it is. PLease helpP.. thanks in advanced. that is when i press the button once the page is generated nothing happens!!




#!/usr/bin/perl
use strict; use warnings;
use CGI qw/:all/;
use CGI::Pretty;
use CGI::Carp "fatalsToBrowser";
use DBI;
my $serverName=;
my $serverPort=;
my $serverUser=;
my $serverPass=;
my $serverDb=;
my $serverTabl=;

if(!param()){
htmlForm();
}else{
my $error=insert_entry();
show_entries($error);
}

sub htmlForm{
print header();
print start_html(-title=>'Lab 6',-scrip=>{-language=>'PerlScript', src=>'mySqlProg.cgi'});
print h1("Enter data in to mysql table(lab 6)");
print startform({-action=>"",-method=>"POST"});
print table(TR(td("First Name:"),td(textfield({-name=>"fname",-size=>"11",-maxlength=>"10"}))),
TR(td("Last Name:"),td(textfield({-name=>"lname",-size=>"11",-maxlength=>"10"}))),
TR(td("Student ID:"),td(textfield({-name=>"id",-size=>"10",-maxlength=>"9"}))),
TR(td("Logins:"),td(textfield({-name=>"logins",-size=>"4",-maxlength=>"3"}))));
print submit(-name=>'submit_form', -value=>'Submit form');
print end_form();
print "<button type='button' value='view' onclick='show_entries();'>Show Table Values</button>";
print "<button type='button' value='increment' onclick='increment();'>Increment logins by 1</button>";
print "<button type='button' value='change' onclick='change();'>Any field, change the # 6 to 4</button>";
print end_html();
}

sub insert_entry {
my ($dbh,$sth,$Fname,$Lname,$studentID,$Logins,$success);
$dbh=DBI->connect("DBI:mysql:database=$serverDb;host=$serverName;port=$serverPort",$serverUser,$serverPass)
or die ("Cant connect to the database: ". DBI->errstr);
$Fname=param("fname");
$Lname=param("lname");
$studentID=param("id");
$Logins=param("logins");
$success=$dbh->do("INSERT INTO $serverTabl(firstname,lastname,SID,logins) VALUES(?,?,?,?)",
undef,$Fname,$Lname,$studentID,$Logins);
$dbh->disconnect;
if($success != 1){return "Sorry, the database was unable to add your entry.";}
}

sub show_entries {
my($dbh, $sth, @row);
$dbh=DBI->connect("DBI:mysql:database=$serverDb;host=$serverName;port=$serverPort",$serverUser,$serverPass);
$sth=$dbh->prepare("SELECT firstname,lastname,SID,logins FROM $serverTabl");
$sth->execute;
print header();
print start_html(-title=>'Lab 6');
if($_){print "$_";}
print "Existing Entries",hr;
while(@row=$sth->fetchrow_array){
print "First Name: ", $row[0], br;
print "Last Name: ", $row[1], br;
print "Student ID: ", $row[2], br;
print "Logins: ", $row[3], br,br;
}
print end_html();
$sth->finish;
$dbh->disconnect;
}

sub increment{
my($dbh);
$dbh=DBI->connect("DBI:mysql:database=$serverDb;host=$serverName;port=$serverPort",$serverUser,$serverPass);
$dbh->do("UPDATE $serverTabl SET logins=logins+1");
$dbh->disconnect;
}

sub change{
my($dbh, $sth, @row);
$dbh=DBI->connect("DBI:mysql:database=$serverDb;host=$serverName;port=$serverPort",$serverUser,$serverPass);
$sth=$dbh->prepare("SELECT firstname,lastname,SID,logins FROM $serverTabl");
while(@row=$sth->fetchrow_array){
for(my $i=0;$i<=3;$i++){
if($row[$i]){
$row[$i]=~s/6/4/g;
}
}
$dbh->do("UPDATE $serverTabl SET firstname=$row[0],lastname=$row[1],SID=$row[2],logins=$row[3]
WHERE firstame=$row[0]");
}
$sth->finish;
$dbh->disconnect;
}

FishMonger
07-29-2009, 03:49 PM
The buttons need to be inside the form definition and their type needs to be 'submit' and you should also set the name attribute. Then you can use the param() method to retrieve the value and call the proper subroutine.

hackYourBrain
07-29-2009, 04:21 PM
Ok thanks for the reply.. I need to be able to call my subs from another sub..as you can see from my cgi.. and I need to be able to call them from outside the form definition..they are not part of the form.. for example if I want to call a sub from an anchor tag in one of my other subs How do I do that??

FishMonger
07-29-2009, 04:27 PM
If you're referring to the sub being called in the onclick handler, then you need to ask your question in the JavaScript area.

If you want to execute a Perl script/subroutine without a form submit button, then you need to ask your question in the Ajax area.

KevinADC
07-29-2009, 06:49 PM
Fish, it looks like he is using PerlScript, which I know next to nothing about myself.

print start_html(-title=>'Lab 6',-scrip=>{-language=>'PerlScript', src=>'mySqlProg.cgi'});


but -scrip should be -script I would think.

These lines look like syntax errors to me:

my $serverName=;
my $serverPort=;
my $serverUser=;
my $serverPass=;
my $serverDb=;
my $serverTabl=;


should be:

my $serverName;
my $serverPort;
my $serverUser;
my $serverPass;
my $serverDb;
my $serverTabl;

That at least makes the script run when fixed.

FishMonger
07-29-2009, 07:27 PM
He's using both. The posted script is Perl, and it loads an external PerlScript file, just like what would be done with an external javascript or css file.

Based on how the question was posed, this issue does not fall under Perl. It should go to a forum dealing with Perlscript or Ajax, or JavaScript (all of which are client side scripting).

KevinADC
07-29-2009, 08:26 PM
He's using both. The posted script is Perl, and it loads an external PerlScript file, just like what would be done with an external javascript or css file.

Based on how the question was posed, this issue does not fall under Perl. It should go to a forum dealing with Perlscript or Ajax, or JavaScript (all of which are client side scripting).

I owe you a margarita. :thumbsup:

hackYourBrain
07-29-2009, 09:04 PM
this is perl scrip posted in the perl section.. if you dont know perl why are u even replying...



These lines look like syntax errors to me:

my $serverName=;
my $serverPort=;
my $serverUser=;
my $serverPass=;
my $serverDb=;
my $serverTabl=;


should be:

my $serverName;
my $serverPort;
my $serverUser;
my $serverPass;
my $serverDb;
my $serverTabl;


no it shouldnt... was initializing those variables to their appropriate values.. I took the values out for obvious reasons.. [comment removed by FishMonger]

and this scrip is not external.. its not called from some html page.. it generates them as you can clearly seeeee

hollyyy

KevinADC
07-29-2009, 09:50 PM
hehehe.... best laugh so far today, Thanks, good luck with your lab.

FishMonger
07-30-2009, 12:05 AM
hackYourBrain,

The answers I gave are the proper solutions for the problem as you described it. If they aren't what you're looking for, then please provide more details of what you need.

All parameters passed/submitted to the script can be accessed via CGI's param() method.

Do you need help in the Perl logic required to take a parameter passed to the script and decide which subroutine to execute?

If not, then please provide more details regarding the server side portions of what you need i.e., the Perl requirements, not the html requirements.

hackYourBrain
07-30-2009, 01:35 AM
ok guys thanks for your help I will take your advice and post in another section .. although I dont see an Ajax section...

and sorry for not being civil.. just a bit frustrated with my Prof.. danm dude wont help me. didnt mean to take it out on you.

Daneil

FishMonger
07-30-2009, 01:45 AM
You can post ajax questions here: http://codingforums.com/forumdisplay.php?f=55

hackYourBrain
08-03-2009, 04:26 AM
Ok since I am having trouble getting some help with this..and I mean some serious trouble.. guess perl is not as popular as I thought.. my Prof wont help me.. tutor couldnt help me.. you guys cant help me.. ok ok sorry there I go again.. it looks like I will have to do it myself I will post my progress here.. so maybe some of you will learn something you can use.. my lab is to code a hockey or soccer or nfl online pool.. with some specs..part of which are to use a database to store and retrieve data.. and use linux commands and regular espressions to work with the system and info.. should be fun considering Im on my own.. but here is what I Have soo far.. My main coner with asking the previouse questions was that I didnt understand what the mechanics were for moving around with perl cgi.. by moving around I mean running webpages base on input ofcourse.. but since we are to use a form for everything It looks like I can do whatever I need with param()... so here it goes.. Will keep you updated..ohh and before anyone asks.. the variables near the top are not initialized for security reasons.. if you want to use this script.. then you will have to plug in your own values.... and dont tell me the script dont work.. of course it dont its under development.. I will say when its completely done.. annd I wil not comment the code in till Im finished.. cause Im on a tight deadline so I cant do it til the end.. cheers



#!/usr/bin/perl
use strict;
use warnings;
use CGI qw/:all/;
use CGI::Pretty;
use CGI::Carp "fatalsToBrowser";
use DBI;
#use LWP::TreeBuilder;
#use LWP::FormatText;
use LWP::Simple;

my $serverName="";
my $serverPort="";
my $serverUser="";
my $serverPass="";
my $serverDb="";
my $serverTabl="mysql";
my($checkBoxValue,$flag,$randomNum,$accountExists,$specialError,$CSV);
my(@errors,@formValues,@accountsDir);

if(!param()){
firstPage();
}
if(param('firstPage') eq "2"){
# do{
# $flag=0;
# regForm(@formValues,@errors,$specialError);
regForm();
# if(param()){
# $formValues[0]=param("fname");
# $formValues[1]=param("lname");
# $formValues[2]=param("email");
# @errors=validate(@formValues);
# if($errors[0]ne""||$errors[1]ne""||$errors[2]ne""||$errors[3]ne""){
# $flag=1;
# }else{
# $randomNum=int(rand(100000));
# @accountsDir=`ls -l ../accounts`;
# foreach(@accountsDir){
# if($_=~/$formValues[1]$randomNum/){
# $specialError=2;
# $accountExists=1;
# $flag=1;
# }
# }
# if($accountExists!=1){
# system("touch ../accounts/$formValues[1]$randomNum.txt");
# $"=",";
# $CSV="@formValues,$randomNum";
# open MYFILE, ">$formValues[1]$randomNum.txt" or die "There was a problem opening the file\n";
# print MYFILE "$CSV";
# close MYFILE;
# }
# }
# }else{
# $specialError=1;
# $flag=1;
# }
# }while($flag==1);
}
if(param('firstPage') eq "1"){
print header();
print start_html();
print "this will be the sign in page";
print end_html();
}


####################################################################
#mirror($URL, $local_filename); #will be using this to mirror scoreboard
#system(mkdir $folder); #syntax for running linux commands from perl cgi
#my randomNum=rand(999); #should be a number between 0 and 998, right?
#$content = get("http://www.sn.no/"); #uses LWP::Simple; #not sure about this still have to check it
######################################################################


sub validate{
my @errors=("","","","");
if(!($_[0]=~/^[a-z]{2,}[ ]*[a-z]$/i)){
$errors[0]="Only alphabetic characters, minimum two characters long";}
if($_[1]!~/^[a-z]{2,}[ ]*[a-z]$/i){
$errors[1]="Only alphabetic characters, minimum two characters long";}
if($_[2]!~/^[a-z:.~?=+&]{1,}@[a-z.]{1,}$/i){ #:/.~?=+&@
$errors[2]="E-mail field only allows the folloing characters: :/.~?=+&@";}
if($_[2]=~/\.\./){
$errors[3]="Two consecutive periods are not allowed!";}
return @errors;
}



sub regForm{
startHTML();
print h1("Registration Form, fill out the stuff!");
if($_[7]==1){
print span({-style=>'Color: red;'},h3('You did not enter anything! Try again.'));
$_[7]="";
}elsif($_[7]==2){
print span({-style=>'Color: red;'},
h3('Its a miracle! your randomly generated Id number and last name already exist! try again.'));
$_[7]="";
}
print startform({-action=>"",-method=>"POST"});
print table(TR(td("First Name:"),td(textfield({-name=>"fname",-size=>"12",-maxlength=>"12",-value=>"$_[0]"})),td($_[3])),
TR(td("Last Name:"),td(textfield({-name=>"lname",-size=>"12",-maxlength=>"12",-value=>"$_[1]"})),td($_[4])),
TR(td("E-Mail:"),td(textfield({-name=>"email",-size=>"24",-maxlength=>"24",-value=>"$_[2]"})),td($_[5],$_[6])));
print submit(-name=>'Submit', -value=>'Submit');
print end_form();
endHTML();
}

sub firstPage{
my %labels = ('1'=>'I am a member. Sign In.','2'=>'Register');
startHTML();
print h1('Welcome to the Assign2 NFL Pool');
print startform({-action=>"",-method=>"POST"});
print checkbox_group(-name=>'firstPage',-values=>['1','2'],-labels=> \%labels,-linebreak=>'true');
print submit(-name=>'submit', -value=>'Submit');
print end_form();
endHTML();
}

sub endHTML{
print end_html();
}

sub startHTML{
print header();
print start_html(-title=>'Assign2 Daniel Nowocien');
}





I

hackYourBrain
08-03-2009, 04:56 AM
sorry also I will be using server side includes.. anyone tell me if they are interested in comments regarind security considerations? its one of my other chapters.

Me

KevinADC
08-03-2009, 05:10 AM
Your script doesn't work and I think those variables need to be initialized.

hackYourBrain
08-03-2009, 07:21 AM
WAW thats some super sophisticated code you wrote there Kev.. I can see that you earned your badge.. Senior Coder... live long and prosper!

FishMonger
08-03-2009, 04:21 PM
sorry also I will be using server side includes.. anyone tell me if they are interested in comments regarind security considerations? its one of my other chapters.

Me

It's been about 10 years since I've used SSI includes (never really had a valid reason for using SSI), but as far as I know, there aren't any security issues on your end. The SSI security issues are a concern for the server administrator.

However, since it's been a long time since I've used SSI, you should do a simple google search for 'ssi security risk'.

FishMonger
08-03-2009, 04:33 PM
Do you what us to help you with the problems in your code? If so, then which problem and what are the errors/warnings that you're receiving?

KevinADC
08-03-2009, 05:40 PM
WAW thats some super sophisticated code you wrote there Kev.. I can see that you earned your badge.. Senior Coder... live long and prosper!

Thank you, live long and prosper.

hackYourBrain
08-04-2009, 02:14 AM
Your welcome Kev.. bbbaahahaha.. hang in the Fish.. your gona be alrighttt//

Will keep you updated..


God

hackYourBrain
08-04-2009, 03:33 AM
Sorry Fish.. there are security reasons alright.. your right most are on the server side.. but it still involves the cgi's.. and we havent really gotten into any more sophisticated methods of coding and security threats.. but there are plenty of them thats for sure... I guess the point for begginers is, make sure your server is properly configured. And sorry fish I will comment the sections I need help with.. I guess to start with perhaps telling me what the proper way would be to mirror a site so I can use a regular expression to search through the html and find the info I need, the constantly updated scoreboard from a reputable website.

Thanks Fish and Kev.... as much as I sound like I dont care.. a really appreciate all your input :D


The Devil

hackYourBrain
08-07-2009, 01:38 AM
Hey guys I havent had a chance to work on this this week as I had two exams.. but now its time to play.. I put in some play today and here is the updated code.. my new problem now is that I get an internal server 500 error when I press the registration form submit button..after entering some values.. I dont get it.. Im using the same methods for the the initial form decisions and it works fine.. if any one has any ideas why I get a 500 please help.. also my server doesnt seem to be logging this error.. and there is no syntax errors.. so Im totaly lost right now.. will have a new update tomorrow with my progress.. as you can see I have decided to use glabal variables.. and Im using param() for all my initial decisions since I dont really know any other methods at this point..

space marine



#!/usr/bin/perl
use strict;
use warnings;
use CGI qw/:all/;
use CGI::Pretty;
use CGI::Carp qw/fatalsToBrowser warningsToBrowser/;
use DBI;
use LWP ":Simple", ":TreeBuilder", ":FormatText";

my $serverName="";
my $serverPort="";
my $serverUser="";
my $serverPass="";
my $serverDb="";
my $serverTabl="";
my($checkBoxValue,$flag,$randomNum,$accountExists,$specialError,$CSV,$firstName,$lastName,$eMail);
my(@errors,@accountsDir);

if(!param()){
firstPage();
}

if(param("hidden") eq "first"){
if(param("firstPage") eq "2"){
regForm();
}elsif(param("firstPage") eq "1"){
print header();
print start_html();
print "this will be the sign in page";
print end_html();
}
}


if(param("hidden") eq "register"){
$firstName=param("fname");
$lastName=param("lname");
$eMail=param("email");
validate();
if($errors[0]ne""||$errors[1]ne""||$errors[2]ne""||$errors[3]ne""||$specialError ne ""){
regForm();
}else{
$randomNum=int(rand(100000));
@accountsDir=`ls -l ../accounts`;
foreach(@accountsDir){
if($_=~/$lastName$randomNum/){
$specialError="Its a miracle! Your randomly generated ID # and last name alredy exist. Try again.";
$flag=1;
}
}
if($flag!=1){
system("touch ../accounts/$lastName$randomNum.txt");
$CSV="$firstName,$lastName,$eMail,$randomNum";
open MYFILE, ">$lastName$randomNum.txt" or die "There was a problem opening the file\n";
print MYFILE "$CSV";
close MYFILE;
}else{regFrom();}
}
}




####################################################################

#mirror($URL, $local_filename); #will be using this to mirror scoreboard
#system(mkdir $folder); #syntax for running linux commands from perl cgi
#my randomNum=rand(999); #should be a number between 0 and 998, right?
#$content = get("http://www.sn.no/"); #uses LWP::Simple;
######################################################################


sub validate{
$errors[0]="";$errors[1]="";$errors[2]="";$errors[3]="";$specialError="";
if($firstName!~/^[a-z]{2,}[ ]*[a-z]$/i){
$errors[0]="Only alphabetic characters, minimum two characters long";}
if($lastName!~/^[a-z]{2,}[ ]*[a-z]$/i){
$errors[1]="Only alphabetic characters, minimum two characters long";}
if($eMail!~/^[a-z:.~?=+&]{1,}@[a-z.]{1,}$/i){ #:/.~?=+&@
$errors[2]="E-mail field only allows the folloing characters: :/.~?=+&@";}
if($eMail=~/\.\./){
$errors[3]="Two consecutive periods are not allowed!";}
}



sub regForm{
startHTML();
print h1($specialError);
print startform({-action=>"",-method=>"POST"});
print table(TR(td("First Name:"),td(textfield({-name=>"fname",-size=>"12",-maxlength=>"12",-value=>"$firstName"})),td($errors[0])),
TR(td("Last Name:"),td(textfield({-name=>"lname",-size=>"12",-maxlength=>"12",-value=>"$lastName"})),td($errors[1])),
TR(td("E-Mail:"),td(textfield({-name=>"email",-size=>"24",-maxlength=>"24",-value=>"$eMail"})),td($errors[2],$errors[3])));
print hidden(-name=>'hidden',-value=>'register');
print submit(-name=>'regForm', -value=>'Submit');
print end_form();
endHTML();
}

sub firstPage{
my %labels = ('1'=>'I am a member. Sign In.','2'=>'Register');
startHTML();
print h1('Welcome to the Assign2 NFL Pool');
print startform({-action=>"",-method=>"POST"});
print checkbox_group(-name=>'firstPage',-values=>['1','2'],-labels=> \%labels,-linebreak=>'true');
print hidden(-name=>'hidden',-value=>'first');
print submit(-name=>'submit', -value=>'Submit');
print end_form();
endHTML();
}

sub endHTML{
print end_html();
}

sub startHTML{
print header();
print start_html(-title=>'Assign2 Daniel Nowocien');
}

hackYourBrain
08-07-2009, 06:36 PM
ok my server was giving me the fatal error thats cousing my script to fail and its this: Premature end of script headers. I looked it up and its telling me that Im not sending the server a header.. but I AMM.. it happens right after I enter some values in to my registration form and hit submit. its like it doesnt even go inside the if condition after the registration form.. but I dont know why.. it works for first page form.

KevinADC
08-07-2009, 06:47 PM
Maybe you uploaded the script in binary mode instead of ASCII/text mode.

hackYourBrain
08-07-2009, 06:57 PM
thanks for the reply Kev.. no thats not it.. haha.. cant help to think your making fun of me.. the script runs fine.. up in till I hit the registration form submit button. Iv narrowed the problem to its not going in to the if condition responisble for handeling the request from the registration form.. i have no idea why. run the script and see for your self.. from browse of course.. since its generating html pages.. under a linux os. which im sure you are familiar with

Thanks
Grasshopper

bazz
08-07-2009, 07:31 PM
Not sure I see what your code is meant to do but surely you don't want to tell it to print a sub?



if(param("hidden") eq "first"){
if(param("firstPage") eq "2"){
regForm();
}elsif(param("firstPage") eq "1"){
print header();
print start_html();
print "this will be the sign in page";
print end_html();
}
}



don't you want to output the sub which has the 'print' instructions in it?

bazz

hackYourBrain
08-07-2009, 10:46 PM
start_html() is a cgi.pm function.. that statement works for sure.. but thanks for trying bazz.. I am making progress.. toon in later today for the updated code and new questions


bobo

bazz
08-07-2009, 11:07 PM
Yeh I was confused by your code. You have start_html() but elsewhere you use start_HTML as a sub, which contains start_html();

bazz

hackYourBrain
08-08-2009, 01:50 AM
ok boys.. its been 9 hours of work today and here is where im at..

the script works.. you can run it but now Im using a database SO I pretty sure your gona get internal server errors if you dont plug in the appropriate values near the top.

next I have to generate a form that will contain values pulled from a cfl schedule website.. I used cfl because they have the least teams so I though I might be easer.. its not.. and Im in Canada so why would I use NFL. I have to use regex to sort through the page source code and get the info I need THEN use that info to generate a dynamic form. I KNOW.. this work is taking place in the predictions() subroutine..I wrote a little cgi to try to test some regex and its not working.. but this was near the end..NOW.. so Im tired. here is



#!/usr/bin/perl
use strict; use warnings; use CGI qw/:all/;
#use LWP ":Simple", ":TreeBuilder", ":FormatText";
use CGI qw/:all/;
use LWP::Simple;
use Data::Dumper;

my $content;
$content = get("http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/scores/live/scoreboard.aspx?date=");

print "$content";

if($content=~/(August [0-9]{1,2}?).*">([A-Z][a-z]{3,} at [A-Z][a-z]{3,},)/g){
print "\$1 is $1","\n","\$2 is $2","\n";
}


if you hit the url you can see the page and the source, to see what I was trying.. If anyone has any suggestions on how I can regular expresion through the source to find what teams are playing and on what date. IT WOULD BE GREAT. this is whats cause me the most pain right now..

and here is the updated main scrip that works nice.. up intill the predictions function ofcourse



#!/usr/bin/perl
use strict;
use warnings;
use CGI qw/:all/;
use CGI::Pretty;
use CGI::Carp qw/fatalsToBrowser warningsToBrowser/;
use DBI;
#use LWP ":Simple", ":TreeBuilder", ":FormatText";
use LWP::Simple;
my $scoresURL="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/scores/live/scoreboard.aspx?date=";
my $augustSchedule="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/stat/monthlysched.aspx?month=8";
my $septemberSchedule="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/stat/monthlysched.aspx?month=9";
my $octoberSchedule="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/stat/monthlysched.aspx?month=10";
my $novemberSchedule="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/stat/monthlysched.aspx?month=11";
my $serverName="";
my $serverPort="";
my $serverUser="";
my $serverPass="";
my $serverDb="";
my $serverTabl="";
my($checkBoxValue,$flag,$randomNum,$accountExists,$specialError,$CSV,$firstName,$lastName,$eMail,$us erID,
$dbh,$sth,$wager,$bet,$balance,$date,$content,$schedulePage,$useSchedule);
my(@errors,@accountsDir,@monthDay);
my @teams=("Winnipeg","Saskatchewan","Toronto","Montreal","Brt Columbia","Edmonton","Hamilton","Calgary")

if(!param()){
firstPage();
}

if(param("first")){
if(param("firstPage") eq "2"){
regForm();
}elsif(param("firstPage") eq "1"){
login();
}
}

if(param("regForm")){
$firstName=param("fname");
$lastName=param("lname");
$eMail=param("email");
validate();
if($errors[0]ne""||$errors[1]ne""||$errors[2]ne""||$errors[3]ne""||$specialError ne ""){
regForm();
}else{
$randomNum=int(rand(100000));
@accountsDir=`ls -l ../accounts`;
foreach(@accountsDir){
if($_=~/$lastName$randomNum/){
$specialError="Its a miracle! Your randomly generated ID # and last name alredy exist. Try again.";
$flag=1;
}
}
if($flag!=1){
system("touch ../accounts/$lastName$randomNum.txt");
$CSV="$firstName,$lastName,$eMail,$randomNum";
open MYFILE, "> ../accounts/$lastName$randomNum.txt" or die "There was a problem opening the file\n";
print MYFILE "$CSV";
close MYFILE;
$dbh=DBI->connect("DBI:mysql:database=$serverDb;host=$serverName;port=$serverPort",$serverUser,$serverPass)
or die ("Cant connect to the database: ". DBI->errstr);
$dbh->do("INSERT INTO $serverTabl(firstname,lastname,accountid,email) VALUES(?,?,?,?)",
undef,$firstName,$lastName,$randomNum,$eMail);
$dbh->disconnect;
success();
}else{regFrom();}
}
}

if(param("LogIn")){
$lastName=param("lname");
$userID=param("id");
if($lastName eq ""){
$specialError="You did not enter a last name, try again.";
login();
}elsif($userID eq ""){
$specialError="You did not enter a user ID, try again.";
login();
}elsif($lastName eq "" && $userID eq ""){
$specialError="You didnt enter anything, try again";
login();
}else{
@accountsDir=`ls -l ../accounts`;
foreach(@accountsDir){
if($_=~/$lastName$userID/){
$flag=1;
}
}
if($flag==1){
welcome();
}else{
$specialError="Either your last name or user ID is invalid, try again.";
login();
}
}
}

if(param("welcome")){
if(param("account")){
#display account values
}elsif(param("predictions")){
#predictions();
}
}


######above in main######below are all functions#############


sub predictions{
$date=`date`;
if($date=~/aug/i){
$useSchedule=$augustSchedule;
}elsif($date=~/sep/i){
$useSchedule=$septemberSchedule;
}elsif($date=~/oct/i){
$useSchedule=$octoberSchedule;
}elsif($date=~/nov/i){
$useSchedule=$novemberSchedule;
}
$schedulePage=get($useSchedule);
if($date=~/([a-z]{3} *?[0-9]{1,2})/i){
@monthDay=split(/ .?/,$1);
}

}

sub welcome{
startHTML();
print h4("Welcome $firstName"),br(),"What would you like to do?",br();
print startform({-action=>"",-method=>"POST"});
print "Check your account? ",checkbox({-name=>'account',-value=>'account',-label=>''}),br();
print "Make predictions? ",checkbox({-name=>'predictions',-value=>'predictions',-label=>''}),br();
print submit(-name=>"welcome",-value=>"welcome",-label=>'submit');
endHTML();
}

sub login{
startHTML();
print h3("Login");
print "$specialError";
print startform({-action=>"",-method=>"POST"});
print textfield({-name=>"lname",-size=>"12",-value=>"$lastName"}),br();
print textfield({-name=>"id",-size=>"12",-value=>"$userID"}),br();
print submit(-name=>"LogIn",-value=>"LogIn"),end_form();
endHTML();
}

sub success{
startHTML();
print h3("You have successfully registered. Here is your information and Login ID."),br();
print "$firstName $lastName",br(),"$eMail",br();
print "Your ID# $randomNum",br();
print a({href=>"http://zenit.senecac.on.ca:16526/cgi-bin/assign2.cgi"},"Return to start page");
print endHTML();
}

sub validate{
$errors[0]="";$errors[1]="";$errors[2]="";$errors[3]="";$specialError="";
if($firstName!~/^[a-z]{2,}[ ]*[a-z]$/i){
$errors[0]="Only alphabetic characters, minimum two characters long";}
if($lastName!~/^[a-z]{2,}[ ]*[a-z]$/i){
$errors[1]="Only alphabetic characters, minimum two characters long";}
if($eMail!~/^[a-z:.~?=+&]{1,}@[a-z.]{1,}$/i){ #:/.~?=+&@
$errors[2]="E-mail field only allows the folloing characters: :/.~?=+&@";}
if($eMail=~/\.\./){
$errors[3]="Two consecutive periods are not allowed!";}
}


sub regForm{
startHTML();
print h1($specialError);
print startform({-action=>"",-method=>"POST"});
print table(TR(td("First Name:"),td(textfield({-name=>"fname",-size=>"12",-maxlength=>"12",-value=>"$firstName"})),td($errors[0])),
TR(td("Last Name:"),td(textfield({-name=>"lname",-size=>"12",-maxlength=>"12",-value=>"$lastName"})),td($errors[1])),
TR(td("E-Mail:"),td(textfield({-name=>"email",-size=>"24",-maxlength=>"24",-value=>"$eMail"})),td($errors[2],$errors[3])));
print hidden(-name=>'hidden',-value=>'register');
print submit(-name=>'regForm', -value=>'register');
print end_form();
endHTML();
}

sub firstPage{
my %labels = ('1'=>'I am a member. Sign In.','2'=>'Register');
startHTML();
print h1('Welcome to the Assign2 NFL Pool');
print startform({-action=>"",-method=>"POST"});
print checkbox_group(-name=>'firstPage',-values=>['1','2'],-labels=> \%labels,-linebreak=>'true');
print hidden(-name=>'hidden',-value=>'first');
print submit(-name=>'first',-value=>'first',-label=>'submit');
print end_form();
endHTML();
}

sub endHTML{
print end_html();
}

sub startHTML{
print header();
print start_html(-title=>'Assign2 Daniel');
}


Thanks for all your help boys.
DukeNukem

KevinADC
08-08-2009, 01:59 AM
You are using strict but then you dclare all your variables in a global context:


my($checkBoxValue,$flag,$randomNum,$accountExists,$specialError,$CSV,$firstName,$lastName,$eMail,$us erID,
$dbh,$sth,$wager,$bet,$balance,$date,$content,$schedulePage,$useSchedule);
my(@errors,@accountsDir,@monthDay);

That pretty much defeats the purpose of using strict in the first place. It will find typographical errors but you can no longer use strict to help with scoping errors since all the variables are global in scope.

FishMonger
08-08-2009, 02:52 AM
I have not look at your code in detail, but you have some problems.


C:\test>perl -c hackYourBrain.pl
Prototype mismatch: sub main::head: none vs ($) at hackYourBrain.pl line 9
Content-type: text/html

<h1>Software error:</h1>
<pre>syntax error at hackYourBrain.pl line 26, near &quot;){&quot;
hackYourBrain.pl had compilation errors.
</pre>
<p>
For help, please send mail to this site's webmaster, giving this error message
and the time and date of the error.

</p>
[Fri Aug 7 18:46:31 2009] hackYourBrain.pl: syntax error at hackYourBrain.pl line 26, near "){"
[Fri Aug 7 18:46:31 2009] hackYourBrain.pl: hackYourBrain.pl had compilation errors.

FishMonger
08-08-2009, 01:19 PM
and here is the updated main scrip that works nice.. up intill the predictions function ofcourse



#!/usr/bin/perl
use strict;
use warnings;
use CGI qw/:all/;
use CGI::Pretty;
use CGI::Carp qw/fatalsToBrowser warningsToBrowser/;
use DBI;
#use LWP ":Simple", ":TreeBuilder", ":FormatText";
use LWP::Simple;
my $scoresURL="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/scores/live/scoreboard.aspx?date=";
my $augustSchedule="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/stat/monthlysched.aspx?month=8";
my $septemberSchedule="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/stat/monthlysched.aspx?month=9";
my $octoberSchedule="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/stat/monthlysched.aspx?month=10";
my $novemberSchedule="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/stat/monthlysched.aspx?month=11";
my $serverName="";
my $serverPort="";
my $serverUser="";
my $serverPass="";
my $serverDb="";
my $serverTabl="";
my($checkBoxValue,$flag,$randomNum,$accountExists,$specialError,$CSV,$firstName,$lastName,$eMail,$us erID,
$dbh,$sth,$wager,$bet,$balance,$date,$content,$schedulePage,$useSchedule);
my(@errors,@accountsDir,@monthDay);
my @teams=("Winnipeg","Saskatchewan","Toronto","Montreal","Brt Columbia","Edmonton","Hamilton","Calgary")

if(!param()){
firstPage();
}

if(param("first")){
if(param("firstPage") eq "2"){
regForm();
}elsif(param("firstPage") eq "1"){
login();
}
}

if(param("regForm")){
$firstName=param("fname");
$lastName=param("lname");
$eMail=param("email");
validate();
if($errors[0]ne""||$errors[1]ne""||$errors[2]ne""||$errors[3]ne""||$specialError ne ""){
regForm();
}else{
$randomNum=int(rand(100000));
@accountsDir=`ls -l ../accounts`;
foreach(@accountsDir){
if($_=~/$lastName$randomNum/){
$specialError="Its a miracle! Your randomly generated ID # and last name alredy exist. Try again.";
$flag=1;
}
}
if($flag!=1){
system("touch ../accounts/$lastName$randomNum.txt");
$CSV="$firstName,$lastName,$eMail,$randomNum";
open MYFILE, "> ../accounts/$lastName$randomNum.txt" or die "There was a problem opening the file\n";
print MYFILE "$CSV";
close MYFILE;
$dbh=DBI->connect("DBI:mysql:database=$serverDb;host=$serverName;port=$serverPort",$serverUser,$serverPass)
or die ("Cant connect to the database: ". DBI->errstr);
$dbh->do("INSERT INTO $serverTabl(firstname,lastname,accountid,email) VALUES(?,?,?,?)",
undef,$firstName,$lastName,$randomNum,$eMail);
$dbh->disconnect;
success();
}else{regFrom();}
}
}

if(param("LogIn")){
$lastName=param("lname");
$userID=param("id");
if($lastName eq ""){
$specialError="You did not enter a last name, try again.";
login();
}elsif($userID eq ""){
$specialError="You did not enter a user ID, try again.";
login();
}elsif($lastName eq "" && $userID eq ""){
$specialError="You didnt enter anything, try again";
login();
}else{
@accountsDir=`ls -l ../accounts`;
foreach(@accountsDir){
if($_=~/$lastName$userID/){
$flag=1;
}
}
if($flag==1){
welcome();
}else{
$specialError="Either your last name or user ID is invalid, try again.";
login();
}
}
}

if(param("welcome")){
if(param("account")){
#display account values
}elsif(param("predictions")){
#predictions();
}
}


######above in main######below are all functions#############


sub predictions{
$date=`date`;
if($date=~/aug/i){
$useSchedule=$augustSchedule;
}elsif($date=~/sep/i){
$useSchedule=$septemberSchedule;
}elsif($date=~/oct/i){
$useSchedule=$octoberSchedule;
}elsif($date=~/nov/i){
$useSchedule=$novemberSchedule;
}
$schedulePage=get($useSchedule);
if($date=~/([a-z]{3} *?[0-9]{1,2})/i){
@monthDay=split(/ .?/,$1);
}

}

sub welcome{
startHTML();
print h4("Welcome $firstName"),br(),"What would you like to do?",br();
print startform({-action=>"",-method=>"POST"});
print "Check your account? ",checkbox({-name=>'account',-value=>'account',-label=>''}),br();
print "Make predictions? ",checkbox({-name=>'predictions',-value=>'predictions',-label=>''}),br();
print submit(-name=>"welcome",-value=>"welcome",-label=>'submit');
endHTML();
}

sub login{
startHTML();
print h3("Login");
print "$specialError";
print startform({-action=>"",-method=>"POST"});
print textfield({-name=>"lname",-size=>"12",-value=>"$lastName"}),br();
print textfield({-name=>"id",-size=>"12",-value=>"$userID"}),br();
print submit(-name=>"LogIn",-value=>"LogIn"),end_form();
endHTML();
}

sub success{
startHTML();
print h3("You have successfully registered. Here is your information and Login ID."),br();
print "$firstName $lastName",br(),"$eMail",br();
print "Your ID# $randomNum",br();
print a({href=>"http://zenit.senecac.on.ca:16526/cgi-bin/assign2.cgi"},"Return to start page");
print endHTML();
}

sub validate{
$errors[0]="";$errors[1]="";$errors[2]="";$errors[3]="";$specialError="";
if($firstName!~/^[a-z]{2,}[ ]*[a-z]$/i){
$errors[0]="Only alphabetic characters, minimum two characters long";}
if($lastName!~/^[a-z]{2,}[ ]*[a-z]$/i){
$errors[1]="Only alphabetic characters, minimum two characters long";}
if($eMail!~/^[a-z:.~?=+&]{1,}@[a-z.]{1,}$/i){ #:/.~?=+&@
$errors[2]="E-mail field only allows the folloing characters: :/.~?=+&@";}
if($eMail=~/\.\./){
$errors[3]="Two consecutive periods are not allowed!";}
}


sub regForm{
startHTML();
print h1($specialError);
print startform({-action=>"",-method=>"POST"});
print table(TR(td("First Name:"),td(textfield({-name=>"fname",-size=>"12",-maxlength=>"12",-value=>"$firstName"})),td($errors[0])),
TR(td("Last Name:"),td(textfield({-name=>"lname",-size=>"12",-maxlength=>"12",-value=>"$lastName"})),td($errors[1])),
TR(td("E-Mail:"),td(textfield({-name=>"email",-size=>"24",-maxlength=>"24",-value=>"$eMail"})),td($errors[2],$errors[3])));
print hidden(-name=>'hidden',-value=>'register');
print submit(-name=>'regForm', -value=>'register');
print end_form();
endHTML();
}

sub firstPage{
my %labels = ('1'=>'I am a member. Sign In.','2'=>'Register');
startHTML();
print h1('Welcome to the Assign2 NFL Pool');
print startform({-action=>"",-method=>"POST"});
print checkbox_group(-name=>'firstPage',-values=>['1','2'],-labels=> \%labels,-linebreak=>'true');
print hidden(-name=>'hidden',-value=>'first');
print submit(-name=>'first',-value=>'first',-label=>'submit');
print end_form();
endHTML();
}

sub endHTML{
print end_html();
}

sub startHTML{
print header();
print start_html(-title=>'Assign2 Daniel');
}


Thanks for all your help boys.
DukeNukem

I don't see how it works nice when it produces the following errors and warnings.


C:\TEMP>perl -c hackYourBrain.pl
Prototype mismatch: sub main::head: none vs ($) at hackYourBrain.pl line 9
[Sat Aug 8 05:14:12 2009] hackYourBrain.pl: "my" variable %labels masks earlier declaration in same scope at hackYourBrain.pl line 189.
Status: 500
Content-type: text/html

<h1>Software error:</h1>
<pre>syntax error at hackYourBrain.pl line 26, near &quot;){&quot;
syntax error at hackYourBrain.pl line 68, near &quot;}&quot;
syntax error at hackYourBrain.pl line 96, near &quot;}&quot;
syntax error at hackYourBrain.pl line 126, near &quot;}&quot;
syntax error at hackYourBrain.pl line 136, near &quot;}&quot;
syntax error at hackYourBrain.pl line 147, near &quot;}&quot;
syntax error at hackYourBrain.pl line 156, near &quot;}&quot;
syntax error at hackYourBrain.pl line 168, near &quot;}&quot;
syntax error at hackYourBrain.pl line 182, near &quot;}&quot;
syntax error at hackYourBrain.pl line 194, near &quot;}&quot;
hackYourBrain.pl has too many errors.
</pre>
<p>
For help, please send mail to this site's webmaster, giving this error message
and the time and date of the error.

</p>
<!-- warning: "my" variable %labels masks earlier declaration in same scope at hackYourBrain.pl line 189. -->
[Sat Aug 8 05:14:12 2009] hackYourBrain.pl: syntax error at hackYourBrain.pl line 26, near "){"
[Sat Aug 8 05:14:12 2009] hackYourBrain.pl: syntax error at hackYourBrain.pl line 68, near "}"
[Sat Aug 8 05:14:12 2009] hackYourBrain.pl: syntax error at hackYourBrain.pl line 96, near "}"
[Sat Aug 8 05:14:12 2009] hackYourBrain.pl: syntax error at hackYourBrain.pl line 126, near "}"
[Sat Aug 8 05:14:12 2009] hackYourBrain.pl: syntax error at hackYourBrain.pl line 136, near "}"
[Sat Aug 8 05:14:12 2009] hackYourBrain.pl: syntax error at hackYourBrain.pl line 147, near "}"
[Sat Aug 8 05:14:12 2009] hackYourBrain.pl: syntax error at hackYourBrain.pl line 156, near "}"
[Sat Aug 8 05:14:12 2009] hackYourBrain.pl: syntax error at hackYourBrain.pl line 168, near "}"
[Sat Aug 8 05:14:12 2009] hackYourBrain.pl: syntax error at hackYourBrain.pl line 182, near "}"
[Sat Aug 8 05:14:12 2009] hackYourBrain.pl: syntax error at hackYourBrain.pl line 194, near "}"
[Sat Aug 8 05:14:12 2009] hackYourBrain.pl: hackYourBrain.pl has too many errors.


I just got into work and need to get a few things done, but when I have more time, I'll look over the code and make some recommendations.

hackYourBrain
08-08-2009, 07:16 PM
Fish .. Kev.. yeah sorry guys I just fixed all those errors.. I screwed up a few places near the end of my day yesterday.. if you run it now its fine..



Prototype mismatch: sub main::head: none vs ($) at hackYourBrain.pl line 9


the above is a direct result of the use LWP::Simple; declaration.. I have tried declaring it several different ways but I still dont know the right way.. although this in not a fatal error and the script does run.. test it.. i think the get() function is from LWP and it works.

here is the scrip with none of those dumb errors.



#!/usr/bin/perl
use strict;
use warnings;
use CGI qw/:all/;
use CGI::Pretty;
use CGI::Carp qw/fatalsToBrowser warningsToBrowser/;
use DBI;
#use LWP ":Simple", ":TreeBuilder", ":FormatText";
use LWP::Simple;
my $scoresURL="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/scores/live/scoreboard.aspx?date=";
my $augustSchedule="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/stat/monthlysched.aspx?month=8";
my $septemberSchedule="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/stat/monthlysched.aspx?month=9";
my $octoberSchedule="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/stat/monthlysched.aspx?month=10";
my $novemberSchedule="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/stat/monthlysched.aspx?month=11";
my $serverName="";
my $serverPort="";
my $serverUser="";
my $serverPass="";
my $serverDb="";
my $serverTabl="";
my($checkBoxValue,$flag,$randomNum,$accountExists,$specialError,$CSV,$firstName,$lastName,$eMail,$us erID,
$dbh,$sth,$wager,$bet,$balance,$date,$content,$schedulePage,$useSchedule);
my(@errors,@accountsDir,@monthDay);
my @teams=("Winnipeg","Saskatchewan","Toronto","Montreal","Brt Columbia","Edmonton","Hamilton","Calgary");

if(!param()){
firstPage();
}

if(param("first")){
if(param("firstPage") eq "2"){
regForm();
}elsif(param("firstPage") eq "1"){
login();
}
}

if(param("regForm")){
$firstName=param("fname");
$lastName=param("lname");
$eMail=param("email");
validate();
if($errors[0]ne""||$errors[1]ne""||$errors[2]ne""||$errors[3]ne""||$specialError ne ""){
regForm();
}else{
$randomNum=int(rand(100000));
@accountsDir=`ls -l ../accounts`;
foreach(@accountsDir){
if($_=~/$lastName$randomNum/){
$specialError="Its a miracle! Your randomly generated ID # and last name alredy exist. Try again.";
$flag=1;
}
}
if($flag!=1){
system("touch ../accounts/$lastName$randomNum.txt");
$CSV="$firstName,$lastName,$eMail,$randomNum";
open MYFILE, "> ../accounts/$lastName$randomNum.txt" or die "There was a problem opening the file\n";
print MYFILE "$CSV";
close MYFILE;
$dbh=DBI->connect("DBI:mysql:database=$serverDb;host=$serverName;port=$serverPort",$serverUser,$serverPass)
or die ("Cant connect to the database: ". DBI->errstr);
$dbh->do("INSERT INTO $serverTabl(firstname,lastname,accountid,email) VALUES(?,?,?,?)",
undef,$firstName,$lastName,$randomNum,$eMail);
$dbh->disconnect;
success();
}else{regFrom();}
}
}

if(param("LogIn")){
$lastName=param("lname");
$userID=param("id");
if($lastName eq ""){
$specialError="You did not enter a last name, try again.";
login();
}elsif($userID eq ""){
$specialError="You did not enter a user ID, try again.";
login();
}elsif($lastName eq "" && $userID eq ""){
$specialError="You didnt enter anything, try again";
login();
}else{
@accountsDir=`ls -l ../accounts`;
foreach(@accountsDir){
if($_=~/$lastName$userID/){
$flag=1;
}
}
if($flag==1){
welcome();
}else{
$specialError="Either your last name or user ID is invalid, try again.";
login();
}
}
}

if(param("welcome")){
if(param("account")){
#display account values
}elsif(param("predictions")){
#predictions();
}
}


######above in main######below are all functions#############


sub predictions{
$date=`date`;
if($date=~/aug/i){
$useSchedule=$augustSchedule;
}elsif($date=~/sep/i){
$useSchedule=$septemberSchedule;
}elsif($date=~/oct/i){
$useSchedule=$octoberSchedule;
}elsif($date=~/nov/i){
$useSchedule=$novemberSchedule;
}
$schedulePage=get($useSchedule);
if($date=~/([a-z]{3} *?[0-9]{1,2})/i){
@monthDay=split(/ .?/,$1);
}

}

sub welcome{
startHTML();
print h4("Welcome $firstName"),br(),"What would you like to do?",br();
print startform({-action=>"",-method=>"POST"});
print "Check your account? ",checkbox({-name=>'account',-value=>'account',-label=>''}),br();
print "Make predictions? ",checkbox({-name=>'predictions',-value=>'predictions',-label=>''}),br();
print submit(-name=>"welcome",-value=>"welcome",-label=>'submit');
endHTML();
}

sub login{
startHTML();
print h3("Login");
print "$specialError";
print startform({-action=>"",-method=>"POST"});
print textfield({-name=>"lname",-size=>"12",-value=>"$lastName"}),br();
print textfield({-name=>"id",-size=>"12",-value=>"$userID"}),br();
print submit(-name=>"LogIn",-value=>"LogIn"),end_form();
endHTML();
}

sub success{
startHTML();
print h3("You have successfully registered. Here is your information and Login ID."),br();
print "$firstName $lastName",br(),"$eMail",br();
print "Your ID# $randomNum",br();
print a({href=>"http://zenit.senecac.on.ca:16526/cgi-bin/assign2.cgi"},"Return to start page");
print endHTML();
}

sub validate{
$errors[0]="";$errors[1]="";$errors[2]="";$errors[3]="";$specialError="";
if($firstName!~/^[a-z]{2,}[ ]*[a-z]$/i){
$errors[0]="Only alphabetic characters, minimum two characters long";}
if($lastName!~/^[a-z]{2,}[ ]*[a-z]$/i){
$errors[1]="Only alphabetic characters, minimum two characters long";}
if($eMail!~/^[a-z:.~?=+&]{1,}@[a-z.]{1,}$/i){ #:/.~?=+&@
$errors[2]="E-mail field only allows the folloing characters: :/.~?=+&@";}
if($eMail=~/\.\./){
$errors[3]="Two consecutive periods are not allowed!";}
}


sub regForm{
startHTML();
print h1($specialError);
print startform({-action=>"",-method=>"POST"});
print table(TR(td("First Name:"),td(textfield({-name=>"fname",-size=>"12",-maxlength=>"12",-value=>"$firstName"})),td($errors[0])),
TR(td("Last Name:"),td(textfield({-name=>"lname",-size=>"12",-maxlength=>"12",-value=>"$lastName"})),td($errors[1])),
TR(td("E-Mail:"),td(textfield({-name=>"email",-size=>"24",-maxlength=>"24",-value=>"$eMail"})),td($errors[2],$errors[3])));
print hidden(-name=>'hidden',-value=>'register');
print submit(-name=>'regForm', -value=>'register');
print end_form();
endHTML();
}

sub firstPage{
my %labels = ('1'=>'I am a member. Sign In.','2'=>'Register');
startHTML();
print h1('Welcome to the Assign2 NFL Pool');
print startform({-action=>"",-method=>"POST"});
print checkbox_group(-name=>'firstPage',-values=>['1','2'],-labels=>\%labels,-linebreak=>'true');
print hidden(-name=>'hidden',-value=>'first');
print submit(-name=>'first',-value=>'first',-label=>'submit');
print end_form();
endHTML();
}

sub endHTML{
print end_html();
}

sub startHTML{
print header();
print start_html(-title=>'Assign2 Daniel');
}


Im gona try to figure out how to regular expresion through that source code now to get the schedule i need.. will keep you updated.. thanks for all your input guys. ohh and about the use of strict and my global variables.. well again im really new to this.. and I think my prof gave us an assignment that is to complicated for the syntax we have learned... and his providing NO help at all I mean NONE.

JohnnyCab

hackYourBrain
08-08-2009, 07:33 PM
also I making some progress with the regex through the source code to get what I need.. here is my test script.. run it... as you can see you get that prototype mismatch error with this script to .. but the syntax is OK and it runs.. so just to prove thats not a major issue at this point.



#!/usr/bin/perl
use strict; use warnings; use CGI qw/:all/;
#use LWP ":Simple", ":TreeBuilder", ":FormatText";
use CGI qw/:all/;
use LWP::Simple;
use Data::Dumper;

my $content; my $URL="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/scores/live/scoreboard.aspx?date=";
$content = get("http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/stat/monthlysched.aspx?month=8");
#mirror($URL, $content);
#print "$content";
my $date=`date`;
my @num;
if($date=~/([a-z]{3} *?[0-9]{1,2})/i){
print "$1","\n";
@num=split(/ .?/,$1);
print "$num[1]","\n";
}else{
print "failed","\n";
}
#print "$content";

if($content=~/(August [0-9]{1,2}?).*">([A-Z][a-z]{3,} at [A-Z][a-z]{3,},)/g){
print "\$1 is $1","\n","\$2 is $2","\n";
}


thanks guys
Mercy

FishMonger
08-08-2009, 07:37 PM
I was going to post a revised version of the script, but remembered that this a lab assignment, so I can't just give you the complete solution. The best I can do is make a few comments and suggestions.

The Prototype mismatch error is due to a conflict between the CGI and LWP::Simple modules. I'll leave it to you to figure out how to fix it.

All of those syntax errors are caused by 1 missing semi-colon. I'll leave it to you to find out where it's missing.

Kevin already mentioned about using only global vars, but I'll mention it again. You really should/need to declare your vars in the smallest scope/block that they require. Using only global vars can introduce subtle bugs which can/will make it more difficult to troubleshoot.

Your individual monthly schedule vars should be combined/converted to a single hash.

Your startHTML and endHTML subs should be removed and you should factor out those calls in the other subs.

Why are you shelling out (the system and backticks calls), especially to 'ls -l' when you only want the filename? That is less efficient and makes the code unportable.

There race condition issues with the method you're using to create the file, but since this is a lab exercise and not a production script, it probably doesn't matter.

You should use the same name for all of your submit buttons and only change the value that it sends. Doing that will make it easy to use a dispatch table, which will help to cleanup the messy if/else blocks. http://en.wikipedia.org/wiki/Dispatch_table

FishMonger
08-08-2009, 07:56 PM
Using a regex to parse html is the wrong approach and in most cases is the worst approach. You should use an html parser.

There are a number of options in this list.
http://search.cpan.org/modlist/World_Wide_Web/HTML

hackYourBrain
08-09-2009, 12:23 AM
Hey Fish.. yeah the lab says to use LWP, TreeBuilder and FormatText.. but for one, FormatText is not installed on the server we are working on so my prof is an dumb ***.. I dont have permissions to intall it.. we have Parser.. but damn if I can figure out how to use it.. I was looking at the example cspan has but I dont get it..this one



The next example prints out the text that is inside the <title> element of an HTML document. Here we start by setting up a start handler. When it sees the title start tag it enables a text handler that prints any text found and an end handler that will terminate parsing as soon as the title end tag is seen:




use HTML::Parser ();

sub start_handler
{
return if shift ne "title";
my $self = shift;
$self->handler(text => sub { print shift }, "dtext");
$self->handler(end => sub { shift->eof if shift eq "title"; },
"tagname,self");
}

my $p = HTML::Parser->new(api_version => 3);
$p->handler( start => \&start_handler, "tagname,self");
$p->parse_file(shift || die) || die $!;
print "\n";


like what is being parsed here.. I dont see a link to a site or a variable with anything in it??

after hours upon hours of research Im starting to get a bit worried.. helppp meeee.

JunBug

FishMonger
08-09-2009, 04:34 PM
Hey Fish.. yeah the lab says to use LWP, TreeBuilder and FormatText.. but for one, FormatText is not installed on the server we are working on so my prof is an dumb ***.. I dont have permissions to intall it..

You could install it in your home directory and use the lib pragma to add your home dir to the @INC path array.
http://search.cpan.org/~smueller/lib-0.62/lib_pm.PL

Or, you could install everything on your home computer and do your testing there instead of the school lab.

If your instructor specified which modules he wants you to use and HTML::Parser is not included in that list, then you may need to stick with his limitations. Did he say that you could use any module you want?

There shouldn't be any problem with using any of the core modules.
http://perldoc.perl.org/index-modules-A.html


In the HTML::Parser example you posted, it's getting the file to be parsed in this line:

$p->parse_file(shift || die) || die $!;
That line uses the shift function to get the filename which is stored in the first element of the @_ or @ARGV array (depending on the scope it's in).
http://perldoc.perl.org/functions/shift.html

hackYourBrain
08-10-2009, 08:19 PM
Thanks fish.. although I must say providing links to official docs is not much help.. i know about the documentation.. but for begginers its rather obscure.. thanks for pointing out where the info is being pulled from.. but that still dont make sense to me.. cause its out side the sub.. so how is it dereferencing $_[1]?? i can see how this would be using it
my $self = shift;

whatever.. i got an appointment with a tutor tomorrow so I will see what happens.. otherwise im screwed. and yes we can use anything we want.. those other modules were just suggestions.. and plus I dont see how pulling text from inside some html tags is any good anywaays.. i still need to use regex to get what i need.. this lab is way to dangoures for begginers.. im really bitter with my prof right now.. I need an A in this damn course otherwise my application for comp eng is not gona look so pretty..


Thanks for your help
Quade

bazz
08-10-2009, 08:29 PM
And I thought tertiary education was different not least because it taught the person how to teach themselves or at least to learn on their own.

I never went there :( and wish I had. But through Fish's (and Kevin's, oesxyl's and other's) post of what you describe as 'links to official docs is not much help', I have got somewhere and it feels good. If I still don't get it and become frustrated, I can ask again here with the little bit of prgorees I have made, thrown in.

It's good also to remember that the people around here who ofer help, do so freely and I am sure it can bug them when someone comes along expecting their help and then who criticises it. Youithful exhuberance has a lot to answer for :D (I am just envious of the young).

bazz

hackYourBrain
08-10-2009, 09:11 PM
And I thought tertiary education was different not least because it taught the person how to teach themselves or at least to learn on their own.

I never went there and wish I had.


huuu?? tertiary? after looking that word up haha.. ammm hahaha.. wooo.. monastic third order hehehehe.. .. ohh mann.. thats some good stuff.. well its never to late I guess.. you can always go.. and its definitely not where I am.. I like to learn from others.. and from the environment ofcourse..



It's good also to remember that the people around here who ofer help, do so freely and I am sure it can bug them when someone comes along expecting their help and then who criticises it.


I agree and apologize. its just that i need answers not redirects to databases. I can look up info just fine.. in most cases better then others.. after all I grew up on the net.. its my home..



Youithful exhuberance has a lot to answer for (I am just envious of the young).


and I dont think exuberance has anything to do with youth.. even though they do like eachother. and I too get nestalgic over my more youthfull and care free years .. but maturity is much more attractive.. I like the death.. I like the misery.. I like this world.. unless ofcourse you live in ignorance of your environment.. i respect ghosts who work for the betterment of socity.. not ignoring the pain.. but embracing it.. as it is part of our very souls.. really hate those who are more concerned about looking good then doing good.. those who close their eyes and live in delusion.. if you cant handle reality .. thats fine.. most cant.. but I wont and cant.. sorry I dont know where I am..

GhostInTheShell

bazz
08-10-2009, 10:51 PM
huuu?? tertiary? after looking that word up haha.. ammm hahaha.. wooo..


I just meant 'third level' education :)
http://en.wikipedia.org/wiki/Tertiary_education.




...I can look up info just fine..


Looks like you looked up the wrong place
http://en.wikipedia.org/wiki/Tertiary
:)

bazz

hackYourBrain
08-11-2009, 12:41 AM
Looks like you looked up the wrong place
http://en.wikipedia.org/wiki/Tertiary


looks like you got me... hehe

Mojo

hackYourBrain
08-12-2009, 01:49 AM
solved my parsing of html source code problem through regex



#!/usr/bin/perl
use strict; use warnings;
use LWP::Simple;

my $content;
$content = get("http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/stat/monthlysched.aspx?month=8");
my $temp;my @data;
$content=~ s/<.*?>//g;
$content=~ s/&nbsp;//g;
($temp,$content)=split(/tNov/,$content);
($content,$temp)=split(/Powered by The Sports Network/,$content);
$temp="";
$content=~ s/[^ A-Za-z0-9,:-]//g;
@data=split(/ {2,}/,$content);
$"="\n";
shift(@data);
print "@data";



inplemented in my main script


#!/usr/bin/perl
use strict;
use warnings;
use CGI qw/:all/;
use CGI::Pretty;
use CGI::Carp qw/fatalsToBrowser warningsToBrowser/;
use DBI;
#use HTML::TreeBuilder;
#use HTML::Parser;
use LWP::Simple;
my $scoresURL="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/scores/live/scoreboard.aspx?date=";
my $augustSchedule="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/stat/monthlysched.aspx?month=8";
my $septemberSchedule="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/stat/monthlysched.aspx?month=9";
my $octoberSchedule="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/stat/monthlysched.aspx?month=10";
my $novemberSchedule="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/stat/monthlysched.aspx?month=11";
my $serverName="";
my $serverPort="";
my $serverUser="";
my $serverPass="";
my $serverDb="";
my $serverTabl="";
my($checkBoxValue,$flag,$randomNum,$accountExists,$specialError,$CSV,$firstName,$lastName,$eMail,$us erID,
$dbh,$sth,$wager,$bet,$balance,$date,$content,$schedulePage,$useSchedule,$temp);
my(@errors,@accountsDir,@monthDay,@data);
my @teams=("Winnipeg","Saskatchewan","Toronto","Montreal","Brt Columbia","Edmonton","Hamilton","Calgary");

if(!param()){
firstPage();
}

if(param("first")){
if(param("firstPage") eq "2"){
regForm();
}elsif(param("firstPage") eq "1"){
login();
}
}

if(param("regForm")){
$firstName=param("fname");
$lastName=param("lname");
$eMail=param("email");
validate();
if($errors[0]ne""||$errors[1]ne""||$errors[2]ne""||$errors[3]ne""||$specialError ne ""){
regForm();
}else{
$randomNum=int(rand(100000));
@accountsDir=`ls -l ../accounts`;
foreach(@accountsDir){
if($_=~/$lastName$randomNum/){
$specialError="Its a miracle! Your randomly generated ID # and last name alredy exist. Try again.";
$flag=1;
}
}
if($flag!=1){
system("touch ../accounts/$lastName$randomNum.txt");
$CSV="$firstName,$lastName,$eMail,$randomNum";
open MYFILE, "> ../accounts/$lastName$randomNum.txt" or die "There was a problem opening the file\n";
print MYFILE "$CSV";
close MYFILE;
$dbh=DBI->connect("DBI:mysql:database=$serverDb;host=$serverName;port=$serverPort",$serverUser,$serverPass)
or die ("Cant connect to the database: ". DBI->errstr);
$dbh->do("INSERT INTO $serverTabl(firstname,lastname,accountid,email) VALUES(?,?,?,?)",
undef,$firstName,$lastName,$randomNum,$eMail);
$dbh->disconnect;
success();
}else{regFrom();}
}
}

if(param("LogIn")){
$lastName=param("lname");
$userID=param("id");
if($lastName eq ""){
$specialError="You did not enter a last name, try again.";
login();
}elsif($userID eq ""){
$specialError="You did not enter a user ID, try again.";
login();
}elsif($lastName eq "" && $userID eq ""){
$specialError="You didnt enter anything, try again";
login();
}else{
@accountsDir=`ls -l ../accounts`;
foreach(@accountsDir){
if($_=~/$lastName$userID.txt/){
$flag=1;
}
}
if($flag==1){
welcome();
}else{
$specialError="Either your last name or user ID is invalid, try again.";
login();
}
}
}

if(param("welcome")){
if(param("account")){
#display account values
}elsif(param("predictions")){
startHTML();
print h3("CFL predictions pool. Make your predictions.");
$date=`date`;
my @date=split(/ /,$date);
$"=" ";
print"Today is: @date", br();
$date[2]+=7;
print b("You can only make predictions up to: $date[1],$date[2]"),br();
predictions();
endHTML();
}
}


######above is main######below are all functions#############


sub predictions{
$date=`date`;
if($date=~/aug/i){
$useSchedule=$augustSchedule;
}elsif($date=~/sep/i){
$useSchedule=$septemberSchedule;
}elsif($date=~/oct/i){
$useSchedule=$octoberSchedule;
}elsif($date=~/nov/i){
$useSchedule=$novemberSchedule;
}
$content=get($useSchedule);
my @date=split(/ /,$date);
$content=~ s/<.*?>//g;
$content=~ s/&nbsp;//g;
($temp,$content)=split(/tNov/,$content);
($content,$temp)=split(/Powered by The Sports Network/,$content); $temp="";
$content=~ s/[^ A-Za-z0-9,:-]//g;
@data=split(/ {2,}/,$content);
shift(@data);
my @data2="@data";
my($day,$month,$dayNum);
my $i=0;my $i2;
foreach(@data){
if($data[$i]=~/[A-Z][a-z]{3,}, [A-Z][a-z]{3,} [0-9]{1,2}/){
($day,$month,$dayNum)=split(/ /,$data[$i]);
if($dayNum >= $date[2] && $dayNum <= ($date[2]+7)){
print"$data[$i]",br();
do{
$i2=$i;
print"$data[$i2+1]",br();
$i2++;
}while($data[$i2]!~/.* at .* /);
}
}
$i++;
}

}

sub welcome{
startHTML();
print h4("Welcome $firstName"),br(),"What would you like to do?";
print startform({-action=>"",-method=>"POST"});
print "Check your account? ",checkbox({-name=>'account',-value=>'account',-label=>''}),br();
print "Make predictions? ",checkbox({-name=>'predictions',-value=>'predictions',-label=>''}),br();
print submit(-name=>"welcome",-value=>"welcome",-label=>'submit');
endHTML();
}

sub login{
startHTML();
print h3("Login");
print "$specialError";
print startform({-action=>"",-method=>"POST"});
print textfield({-name=>"lname",-size=>"12",-value=>"$lastName"}),br();
print textfield({-name=>"id",-size=>"12",-value=>"$userID"}),br();
print submit(-name=>"LogIn",-value=>"LogIn"),end_form();
endHTML();
}

sub success{
startHTML();
print h3("You have successfully registered. Here is your information and Login ID."),br();
print "$firstName $lastName",br(),"$eMail",br();
print "Your ID# $randomNum",br();
print a({href=>"http://zenit.senecac.on.ca:16526/cgi-bin/assign2.cgi"},"Return to start page");
print endHTML();
}

sub validate{
$errors[0]="";$errors[1]="";$errors[2]="";$errors[3]="";$specialError="";
if($firstName!~/^[a-z]{2,}[ ]*[a-z]$/i){
$errors[0]="Only alphabetic characters, minimum two characters long";}
if($lastName!~/^[a-z]{2,}[ ]*[a-z]$/i){
$errors[1]="Only alphabetic characters, minimum two characters long";}
if($eMail!~/^[a-z:.~?=+&]{1,}@[a-z.]{1,}$/i){ #:/.~?=+&@
$errors[2]="E-mail field only allows the folloing characters: :/.~?=+&@";}
if($eMail=~/\.\./){
$errors[3]="Two consecutive periods are not allowed!";}
}


sub regForm{
startHTML();
print h1($specialError);
print startform({-action=>"",-method=>"POST"});
print table(TR(td("First Name:"),td(textfield({-name=>"fname",-size=>"12",-maxlength=>"12",-value=>"$firstName"})),td($errors[0])),
TR(td("Last Name:"),td(textfield({-name=>"lname",-size=>"12",-maxlength=>"12",-value=>"$lastName"})),td($errors[1])),
TR(td("E-Mail:"),td(textfield({-name=>"email",-size=>"24",-maxlength=>"24",-value=>"$eMail"})),td($errors[2],$errors[3])));
print hidden(-name=>'hidden',-value=>'register');
print submit(-name=>'regForm', -value=>'register');
print end_form();
endHTML();
}

sub firstPage{
my %labels = ('1'=>'I am a member. Sign In.','2'=>'Register');
startHTML();
print h1('Welcome to the Assign2 NFL Pool');
print startform({-action=>"",-method=>"POST"});
print checkbox_group(-name=>'firstPage',-values=>['1','2'],-labels=>\%labels,-linebreak=>'true');
print hidden(-name=>'hidden',-value=>'first');
print submit(-name=>'first',-value=>'first',-label=>'submit');
print end_form();
endHTML();
}

sub endHTML{
print end_html();
}

sub startHTML{
print header();
print start_html(-title=>'Assign2 Daniel');
}



tDOT

FishMonger
08-13-2009, 04:00 AM
Glad to hear that you solved the parsing problem.

Please keep us informed, I'd be interested in knowing your instructors comments and the grade he gives you. After that, if you wish, I may post my version.

hackYourBrain
08-13-2009, 04:41 AM
your version of what? comments of my assignment or your own cfl pool script? lol if you have a simple working version that you were holding out on me I would be very upset.. hahaha....just kidding.. but it would be mean on your part for sure though... no im just kiidding.. ha ha.. but seriously though? this is gona be a close call cause i have till sunday night to complete this script and I have my final monday.. sooooo i mean II would like to study aaa bittt and if you were gona throw in some code in there.. it wouldnt hurt.. although i guess it wont matter at this point.. case im already going in a certain direction.. i couldnt use any of your stuff now anyways.. it feels as if i just keeping typing and there is nothing good coming out.. like coMPuteR CodeE..


I can see the liighTT.. and it BUrnnsss!!

homeSlice

FishMonger
08-13-2009, 01:12 PM
I have not worked up any code yet, because I didn't want to post a full solution to your homework assignment. However, I'll work up a new version based on all of the suggestions that I made in this thread and will post it Monday or Tuesday. I'm not sure if I have all of parameters for your assignment, but the solution will be based on what you have stated.

hackYourBrain
08-14-2009, 01:49 AM
update.. its coming along nice now.. still lots of work ahead.. im ignoring all validation specifications since i dont have enough time.. will try to completely finish this tomorrow..



#!/usr/bin/perl
use strict;
use warnings;
use CGI qw/:standard :html3/;
use CGI::Pretty;
use CGI::Carp qw/fatalsToBrowser warningsToBrowser/;
use DBI;
#use HTML::TreeBuilder;
#use HTML::Parser;
use LWP::Simple;
my $scoresURL="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/scores/live/scoreboard.aspx?date=";
my $augustSchedule="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/stat/monthlysched.aspx?month=8";
my $septemberSchedule="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/stat/monthlysched.aspx?month=9";
my $octoberSchedule="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/stat/monthlysched.aspx?month=10";
my $novemberSchedule="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/stat/monthlysched.aspx?month=11";
my $serverName="";
my $serverPort="";
my $serverUser="";
my $serverPass="";
my $serverDb="";
my $serverTabl="";
my($checkBoxValue,$flag,$randomNum,$accountExists,$specialError,$CSV,$firstName,$lastName,$eMail,$us erID,
$dbh,$sth,$wager,$bet,$balance,$date,$content,$schedulePage,$useSchedule,$temp,$Count);
my(@errors,@accountsDir,@monthDay,@data,@data2,@row);
my @teams=("Winnipeg","Saskatchewan","Toronto","Montreal","Brt Columbia","Edmonton","Hamilton","Calgary");

if(!param()){
firstPage();
}

if(param("first")){
if(param("firstPage") eq "2"){
regForm();
}elsif(param("firstPage") eq "1"){
login();
}
}

if(param("regForm")){
$firstName=param("fname");
$lastName=param("lname");
$eMail=param("email");
validate();
if($errors[0]ne""||$errors[1]ne""||$errors[2]ne""||$errors[3]ne""||$specialError ne ""){
regForm();
}else{
$randomNum=int(rand(100000));
@accountsDir=`ls -l ../accounts`;
foreach(@accountsDir){
if($_=~/$lastName$randomNum/){
$specialError="Its a miracle! Your randomly generated ID # and last name alredy exist. Try again.";
$flag=1;
}
}
if($flag!=1){
system("touch ../accounts/$lastName$randomNum.txt");
$CSV="$firstName,$lastName,$eMail,$randomNum";
open MYFILE, "> ../accounts/$lastName$randomNum.txt" or die "There was a problem opening the file\n";
print MYFILE "$CSV";
close MYFILE;
$dbh=DBI->connect("DBI:mysql:database=$serverDb;host=$serverName;port=$serverPort",$serverUser,$serverPass)
or die ("Cant connect to the database: ". DBI->errstr);
$dbh->do("INSERT INTO $serverTabl(firstname,lastname,accountid,email,balance) VALUES(?,?,?,?,?)",
undef,$firstName,$lastName,$randomNum,$eMail,"100");
$dbh->disconnect;
success();
}else{regFrom();}
}
}

if(param("LogIn")){
$lastName=param("lname");
$userID=param("id");
if($lastName eq ""){
$specialError="You did not enter a last name, try again.";
login();
}elsif($userID eq ""){
$specialError="You did not enter a user ID, try again.";
login();
}elsif($lastName eq "" && $userID eq ""){
$specialError="You didnt enter anything, try again";
login();
}else{
@accountsDir=`ls -l ../accounts`;
foreach(@accountsDir){
if($_=~/$lastName$userID.txt/){
$flag=1;
}
}
if($flag==1){
welcome($userID,$lastName);
}else{
$specialError="Either your last name or user ID is invalid, try again.";
login();
}
}
}

if(param("welcome")){
if(param("account")){
resultsPage();
}elsif(param("predictions")){
prediction();
}
}

if(param("prediction")){
predictionsResults();
}

if(param("predictionsResults")){
if(param("correct") eq "yes"){
storePredictions();
welcome();
}else{
prediction();
}

}


######above is main######below are all functions#############

sub resultsPage{
my($currentUserId,$currentUserLastName);
$currentUserId=param("currentUserId");$currentUserLastName=param("currentUserLastName");
startHTML();
print h4("Here are your prediction results and overall standing.");
$dbh=DBI->connect("DBI:mysql:database=$serverDb;host=$serverName;port=$serverPort",$serverUser,$serverPass)
or die ("Cant connect to the database: ". DBI->errstr);
$sth=$dbh->prepare("SELECT firstname,lastname,accountid FROM $serverTabl WHERE date IS NULL");
$sth->execute();
@row=$sth->fetchrow_array();
print b("$row[0]"),' ',b("$row[1]"),br(),b("Userid: $row[2]"),br();
$sth->finish();
$date=`date`;
my @date=split(/ /,$date);
$content=get($useSchedule);
@date=split(/ /,$date);
$content=~ s/<.*?>//g;
$content=~ s/&nbsp;//g;
($temp,$content)=split(/tNov/,$content);
($content,$temp)=split(/Powered by/i,$content); $temp="";
$content=~ s/[^ A-Za-z0-9,:-]//g;
@data=split(/ {2,}/,$content);
shift(@data);
@data2=@data;
my($day,$month,$dayNum);
my $i=0; my($team1,$team2,$i2,$team1name,$team1score,$team2name,$team2score,$dateOfMatch);
$Count=1;
foreach(@data){
if($data[$i]=~/[A-Z][a-z]{3,}, [A-Z][a-z]{3,} [0-9]{1,2}/){
($day,$month,$dayNum)=split(/ /,$data[$i]);
if($dayNum < $date[2]){
$dateOfMatch=$data[$i];
if($data[$i+1]=~/[a-z]{1,} [0-9]{1,2} - [a-z]{1,} [0-9]{1,2}/i){
($team1,$team2)=split(/ - /,$data[$i+1]);
($team1name,$team1score)=split(/ /,$team1);
($team2name,$team2score)=split(/ /,$team2);
#####from here im gona pull values from data base and compare them with above to see if predictions
#####were correct or not will total balance as well for all users.
}
}
}
$i++;
}

endHTML();
$dbh->disconnect();
}



sub storePredictions{
my($currentUserId,$currentUserLastName); my(@values);
$currentUserId=param("currentUserId");$currentUserLastName=param("currentUserLastName");
$dbh=DBI->connect("DBI:mysql:database=$serverDb;host=$serverName;port=$serverPort",$serverUser,$serverPass)
or die ("Cant connect to the database: ". DBI->errstr);
$Count=1;
do{
$values[0]=param("match$Count");
$values[1]=param("wager$Count");
$values[2]=param("bet$Count");
$values[3]=param("date$Count");
$dbh->do("INSERT INTO $serverTabl(accountid,date,team,wager,bet) VALUES(?,?,?,?,?)",
undef,$currentUserId,$values[3],$values[0],$values[1],$values[2]);
$Count++;
}while(param("match$Count"));
$dbh->disconnect;
}



sub predictionsResults{
my($currentUserId,$currentUserLastName);
$currentUserId=param("currentUserId");$currentUserLastName=param("currentUserLastName");
my(@values,@headings,@rows);
startHTML();
print startform({-action=>"",-method=>"POST"});
@headings = ('Team','Result','Wager');
@rows = th(\@headings);
$Count=1;
do{
$values[0]=param("match$Count");
$values[1]=param("matchwager$Count");
$values[2]=param("windrawloss$Count");
$values[3]=param("dateOfMatch$Count");
print hidden(-name=>"match$Count",-value=>"$values[0]"),hidden(-name=>"wager$Count",-value=>"$values[1]"),
hidden(-name=>"bet$Count",-value=>"$values[2]"),hidden(-name=>"date$Count",-value=>"$values[3]");
push(@rows,td([$values[0],$values[2],$values[1]]));
$Count++;
}while(param("match$Count"));
print table({-border=>"1",-width=>'25%'},caption(b('Here are your predictions.')),Tr(\@rows));
print br(),br(),"Is this correct?",br();
print checkbox(-name=>'correct',-value=>'yes',-label=>'Yes');
print checkbox(-name=>'correct',-value=>'no',-label=>'No');
print hidden(-name=>"currentUserId",-value=>"$currentUserId"),hidden(-name=>"currentUserLastName",-value=>"$currentUserLastName");
print submit(-name=>"predictionsResults",-value=>"predictionsResults",-label=>'submit'),end_form();
endHTML();
}

sub prediction{
my($currentUserId,$currentUserLastName);
$currentUserId=param("currentUserId");$currentUserLastName=param("currentUserLastName");
startHTML();
print h3("CFL predictions pool. Make your predictions.");
$date=`date`;
my @date=split(/ /,$date);
$"=" ";
print"Today is: @date", br();
$date[2]+=7;
print b("You can only make predictions up to: $date[1],$date[2]"),br(),br();
if($date=~/aug/i){
$useSchedule=$augustSchedule;
}elsif($date=~/sep/i){
$useSchedule=$septemberSchedule;
}elsif($date=~/oct/i){
$useSchedule=$octoberSchedule;
}elsif($date=~/nov/i){
$useSchedule=$novemberSchedule;
}
$content=get($useSchedule);
@date=split(/ /,$date);
$content=~ s/<.*?>//g;
$content=~ s/&nbsp;//g;
($temp,$content)=split(/tNov/,$content);
($content,$temp)=split(/Powered by/i,$content); $temp="";
$content=~ s/[^ A-Za-z0-9,:-]//g;
@data=split(/ {2,}/,$content);
shift(@data);
@data2=@data;
my($day,$month,$dayNum);
my $i=0; my($team1,$team2,$i2);
$Count=1;
print startform({-action=>"",-method=>"POST"});
foreach(@data){
if($data[$i]=~/[A-Z][a-z]{3,}, [A-Z][a-z]{3,} [0-9]{1,2}/){
($day,$month,$dayNum)=split(/ /,$data[$i]);
if($dayNum >= $date[2] && $dayNum <= ($date[2]+7)){
print hidden(-name=>"dateOfMatch$Count",-value=>"$data[$i]");
print"Match:$Count",br(),$data[$i],br(),"$data[$i+1]";
$data2[$i+1]=substr($data2[$i+1],0,index($data[$i+1],","));
($team1,$team2)=split(/ at /,$data2[$i+1]);
print popup_menu(-name=>"match$Count",-values=>[$team1,$team2]),br();
print "Wager:",popup_menu(-name=>"matchwager$Count",-values=>[qw(2 3 4 5)]),br();
print radio_group(-name=>"windrawloss$Count",-values=>['Win','Draw','Loss'],-linebreak=>'true'),br();
$Count++;
if($data[$i+2]=~ /.* at .*/){
print hidden(-name=>"dateOfMatch$Count",-value=>"$data[$i]");
print"Match:$Count",br(),$data[$i],br(),"$data[$i+2]";
$data2[$i+2]=substr($data2[$i+2],0,index($data[$i+2],","));
($team1,$team2)=split(/ at /,$data2[$i+2]);
print popup_menu(-name=>"match$Count",-values=>[$team1,$team2]),br();
print "Wager:",popup_menu(-name=>"matchwager$Count",-values=>[qw(2 3 4 5)]),br();
print radio_group(-name=>"windrawloss$Count",-values=>['Win','Draw','Loss'],-linebreak=>'true'),br();
$Count++;
}
}
}
$i++;
}
print hidden(-name=>"currentUserId",-value=>"$currentUserId"),hidden(-name=>"currentUserLastName",-value=>"$currentUserLastName");
print submit(-name=>"prediction",-value=>"prediction",-label=>'submit'),end_form();
}


sub welcome{
my($currentUserId,$currentUserLastName);
$currentUserId=param("currentUserId");$currentUserLastName=param("currentUserLastName");
startHTML();
print h4("Welcome user# $_[0]$currentUserId"),br(),"What would you like to do?";
print startform({-action=>"",-method=>"POST"});
print "Check your account? ",checkbox({-name=>'account',-value=>'account',-label=>''}),br();
print "Make predictions? ",checkbox({-name=>'predictions',-value=>'predictions',-label=>''}),br();
print hidden(-name=>"currentUserId",-value=>"$_[0]"),hidden(-name=>"currentUserLastName",-value=>"$_[1]");
print submit(-name=>"welcome",-value=>"welcome",-label=>'submit'),end_form();
endHTML();
}

sub login{
startHTML();
print h3("Login");
print "$specialError";
print startform({-action=>"",-method=>"POST"});
print textfield({-name=>"lname",-size=>"12",-value=>"$lastName"}),br();
print textfield({-name=>"id",-size=>"12",-value=>"$userID"}),br();
print submit(-name=>"LogIn",-value=>"LogIn"),end_form();
endHTML();
}

sub success{
startHTML();
print h3("You have successfully registered. Here is your information and Login ID."),br();
print "$firstName $lastName",br(),"$eMail",br();
print "Your ID# $randomNum",br();
print a({href=>"http://zenit.senecac.on.ca:16526/cgi-bin/assign2.cgi"},"Return to start page");
print endHTML();
}

sub validate{
$errors[0]="";$errors[1]="";$errors[2]="";$errors[3]="";$specialError="";
if($firstName!~/^[a-z]{2,}[ ]*[a-z]$/i){
$errors[0]="Only alphabetic characters, minimum two characters long";}
if($lastName!~/^[a-z]{2,}[ ]*[a-z]$/i){
$errors[1]="Only alphabetic characters, minimum two characters long";}
if($eMail!~/^[a-z:.~?=+&]{1,}@[a-z.]{1,}$/i){ #:/.~?=+&@
$errors[2]="E-mail field only allows the folloing characters: :/.~?=+&@";}
if($eMail=~/\.\./){
$errors[3]="Two consecutive periods are not allowed!";}
}


sub regForm{
startHTML();
print h1($specialError);
print startform({-action=>"",-method=>"POST"});
print table(TR(td("First Name:"),td(textfield({-name=>"fname",-size=>"12",-maxlength=>"12",-value=>"$firstName"})),td($errors[0])),
TR(td("Last Name:"),td(textfield({-name=>"lname",-size=>"12",-maxlength=>"12",-value=>"$lastName"})),td($errors[1])),
TR(td("E-Mail:"),td(textfield({-name=>"email",-size=>"24",-maxlength=>"24",-value=>"$eMail"})),td($errors[2],$errors[3])));
print hidden(-name=>'hidden',-value=>'register');
print submit(-name=>"regForm", -value=>"register");
print end_form();
endHTML();
}

sub firstPage{
my %labels = ('1'=>'I am a member. Sign In.','2'=>'Register');
startHTML();
print h1('Welcome to the Assign2 CFL Pool');
print startform({-action=>"",-method=>"POST"});
print checkbox_group(-name=>'firstPage',-values=>['1','2'],-labels=>\%labels,-linebreak=>'true');
print hidden(-name=>"hidden",-value=>"first");
print submit(-name=>'first',-value=>'first',-label=>'submit');
print end_form();
endHTML();
}

sub endHTML{
print end_html();
}

sub startHTML{
print header();
print start_html(-title=>'Assign2 Daniel');
}



zeroCool

hackYourBrain
08-15-2009, 12:40 AM
ok Fish.. im about to commit suicide im starting to hate perl and sql so can you please tell me why the damn where clause dont work.. i have tried ever combination of this crap i can think off.. where dont work for nothing..it works with out the where no problem.. but i need it



$dbh->do("insert into $serverTabl (accountid,date,team,wager,bet) values($currentUserId,$values[3],$values[0],$values[1],$values[2]) WHERE date <> $values[3]");

$dbh->do("INSERT INTO $serverTabl(accountid,date,team,wager,bet) VALUES(?,?,?,?,?) WHERE date <> ?",
undef,$currentUserId,$values[3],$values[0],$values[1],$values[2],$values[3]);

$dbh->do("INSERT INTO $serverTabl(accountid,date,team,wager,bet) VALUES(?,?,?,?,?) WHERE date <> $values[3]",
undef,$currentUserId,$values[3],$values[0],$values[1],$values[2]);

$dbh->do(qq\insert into $serverTabl (accountid,date,team,wager,bet) values("$currentUserId","$values[3]","$values[0]","$values[1]","$values[2]") WHERE date <> "$values[3]"\);


none of these work..

the error i get is


DBD::mysql::db do failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE date <> 'Friday August 21'' at line 1


it dont make sense. please give me the correct syntax.. and yes I tried !=


Screwed

FishMonger
08-15-2009, 01:13 AM
Try doing it like this:

my $dbh = DBI->connect("DBI:mysql:$serverDb:$serverName",
$serverUser,$serverPass, { RaiseError => 1 } )
or die ("Cant connect to the database: " . DBI->errstr);

my $sth = $dbh->prepare("INSERT INTO $serverTabl(accountid,date,team,wager,bet)
VALUES(?,?,?,?,?) WHERE date <> $values[3]");

$sth->execute($currentUserId,$values[3],$values[0],$values[1],$values[2]);

If that still fails, then print out the statement to see exactly what it's sending to mysql.

hackYourBrain
08-15-2009, 01:37 AM
ok that still dont work..

you mean print the statement like this


print "$sth->execute($currentUserId,$values[3],$values[0],$values[1],$values[2]);";



my output is.. not sure what this means except that my variables are being interpolated properly


DBI::st=HASH(0x8559b0c)->execute(86370,Friday August 14,Brt Columbia,2,Loss);


same error in server error_log


DBD::mysql::st execute failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE date <>' at line 2



Thanks for your prompt reply.. i think im gona give up for today.. been here since 11 am.. i have tomorrow to make this work.. else i give up and lose marks.. i need time to study sunday and monday..

here is my current code.. im trying to make that insert statemnt work for the storePredictions() function.. its the simpler one cause i need a more complicated version of the "where" in the resultsPage() function.. ohh man. Ill be back bright and early tomorrow.. thanks for all your help Fish.. I guess your the only one who knows perl here.. haha out of the thousands of users.. waw..



#!/usr/bin/perl
use strict;
use warnings;
use CGI qw/:standard :html3/;
use CGI::Pretty;
use CGI::Carp qw/fatalsToBrowser warningsToBrowser/;
use DBI;
#use HTML::TreeBuilder;
#use HTML::Parser;
use LWP::Simple;
my $scoresURL="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/scores/live/scoreboard.aspx?date=";
my $augustSchedule="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/stat/monthlysched.aspx?month=8";
my $septemberSchedule="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/stat/monthlysched.aspx?month=9";
my $octoberSchedule="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/stat/monthlysched.aspx?month=10";
my $novemberSchedule="http://scoreboards.canoe.ca/merge/tsnform.aspx?c=canoe&page=cfl/stat/monthlysched.aspx?month=11";
my $serverName="";
my $serverPort="";
my $serverUser="";
my $serverPass="";
my $serverDb="";
my $serverTabl="";
my($checkBoxValue,$flag,$randomNum,$accountExists,$specialError,$CSV,$firstName,$lastName,$eMail,$us erID,
$dbh,$sth,$wager,$bet,$balance,$date,$content,$schedulePage,$useSchedule,$temp,$Count);
my(@errors,@accountsDir,@monthDay,@data,@data2,@row);
my @teams=("Winnipeg","Saskatchewan","Toronto","Montreal","Brt Columbia","Edmonton","Hamilton","Calgary");

if(!param()){
firstPage();
}

if(param("first")){
if(param("firstPage") eq "2"){
regForm();
}elsif(param("firstPage") eq "1"){
login();
}
}

if(param("regForm")){
$firstName=param("fname");
$lastName=param("lname");
$eMail=param("email");
validate();
if($errors[0]ne""||$errors[1]ne""||$errors[2]ne""||$errors[3]ne""||$specialError ne ""){
regForm();
}else{
$randomNum=int(rand(100000));
@accountsDir=`ls -l ../accounts`;
foreach(@accountsDir){
if($_=~/$lastName$randomNum/){
$specialError="Its a miracle! Your randomly generated ID # and last name alredy exist. Try again.";
$flag=1;
}
}
if($flag!=1){
system("touch ../accounts/$lastName$randomNum.txt");
$CSV="$firstName,$lastName,$eMail,$randomNum";
open MYFILE, "> ../accounts/$lastName$randomNum.txt" or die "There was a problem opening the file\n";
print MYFILE "$CSV";
close MYFILE;
$dbh=DBI->connect("DBI:mysql:database=$serverDb;host=$serverName;port=$serverPort",$serverUser,$serverPass)
or die ("Cant connect to the database: ". DBI->errstr);
$dbh->do("INSERT INTO $serverTabl(firstname,lastname,accountid,email,balance) VALUES(?,?,?,?,?)",
undef,$firstName,$lastName,$randomNum,$eMail,"100");
$dbh->disconnect;
success();
}else{regFrom();}
}
}

if(param("LogIn")){
$lastName=param("lname");
$userID=param("id");
if($lastName eq ""){
$specialError="You did not enter a last name, try again.";
login();
}elsif($userID eq ""){
$specialError="You did not enter a user ID, try again.";
login();
}elsif($lastName eq "" && $userID eq ""){
$specialError="You didnt enter anything, try again";
login();
}else{
@accountsDir=`ls -l ../accounts`;
foreach(@accountsDir){
if($_=~/$lastName$userID.txt/){
$flag=1;
}
}
if($flag==1){
welcome($userID,$lastName);
}else{
$specialError="Either your last name or user ID is invalid, try again.";
login();
}
}
}

if(param("welcome")){
if(param("account")){
resultsPage();
}elsif(param("predictions")){
prediction();
}
}

if(param("prediction")){
predictionsResults();
}

if(param("predictionsResults")){
if(param("correct") eq "yes"){
storePredictions();
# welcome();
}else{
prediction();
}

}


######above is main######below are all functions#############

sub resultsPage{
my($currentUserId,$currentUserLastName,$sth2,$sth3);
$currentUserId=param("currentUserId");$currentUserLastName=param("currentUserLastName");
startHTML();
print h4("Here are your prediction results and overall standing.");
$dbh=DBI->connect("DBI:mysql:database=$serverDb;host=$serverName;port=$serverPort",$serverUser,$serverPass)
or die ("Cant connect to the database: ". DBI->errstr);
$sth=$dbh->prepare("SELECT firstname,lastname,accountid FROM $serverTabl WHERE date IS NULL");
$sth->execute();
@row=$sth->fetchrow_array();
print b("$row[0]"),' ',b("$row[1]"),br(),b("Userid: $row[2]"),br();
$sth->finish();
$date=`date`;
my @date=split(/ /,$date);
$content=get($useSchedule);
@date=split(/ /,$date);
$content=~ s/<.*?>//g;
$content=~ s/&nbsp;//g;
($temp,$content)=split(/tNov/,$content);
($content,$temp)=split(/Powered by/i,$content); $temp="";
$content=~ s/[^ A-Za-z0-9,:-]//g;
@data=split(/ {2,}/,$content);
shift(@data);
@data2=@data;
my @dateTeamWagerBet;
my($day,$month,$dayNum); my $i=0;
my($team1,$team2,$i2,$team1name,$team1score,$team2name,$team2score,$dateOfMatch,$teamWon,$teamLost,$ success,$correct);
$Count=1;
$sth2=$dbh->prepare("SELECT date,team,wager,bet,balance FROM $serverTabl WHERE accountid=$currentUserId");
foreach(@data){
if($data[$i]=~/[A-Z][a-z]{3,}, [A-Z][a-z]{3,} [0-9]{1,2}/){
($day,$month,$dayNum)=split(/ /,$data[$i]);
if($dayNum < $date[2]){
$dateOfMatch=$data[$i];
$dateOfMatch=~ s/,//;
if($data[$i+1]=~/[a-z]{1,} [0-9]{1,2} - [a-z]{1,} [0-9]{1,2}/i){
($team1,$team2)=split(/ - /,$data[$i+1]);
($team1name,$team1score)=split(/ /,$team1);
($team2name,$team2score)=split(/ /,$team2);
if($team1score>$team2score){
$teamWon=$team1name;
$teamLost=$team2name;
}elsif($team1score<$team2score){
$teamWon=$team2name;
$teamLost=$team1name;
}else{
$teamWon="Draw";
$teamLost="Draw";
}
$sth2->execute();
while(@dateTeamWagerBet=$sth2->fetchrow_array()){
if($dateTeamWagerBet[0] eq $dateOfMatch){
if($teamWon eq $dateTeamWagerBet[1] && $dateTeamWagerBet[3] eq "Win"){
$success=$dbh->do("UPDATE $serverTabl set balance=$dateTeamWagerBet[2] WHERE date=$dateOfMatch AND team=$teamWon AND
balance is NULL");
}elsif($teamLost eq $dateTeamWagerBet[1] && $dateTeamWagerBet[3] eq "Loss"){
$success=$dbh->do("UPDATE $serverTabl set balance=$dateTeamWagerBet[2] WHERE date=$dateOfMatch AND team=$teamLost AND
balance is NULL");
}elsif(($teamWon eq $dateTeamWagerBet[1] || $teamLost eq $dateTeamWagerBet[1]) && $dateTeamWagerBet[3] eq "Draw"){
$success=$dbh->do("UPDATE $serverTabl set balance=$dateTeamWagerBet[2] WHERE date=$dateOfMatch AND
team=$teamWon OR team=$teamLost AND bet='Draw' AND balance is NULL");
}
}
}
}
if($data[$i+2]=~/[a-z]{1,} [0-9]{1,2} - [a-z]{1,} [0-9]{1,2}/i){
($team1,$team2)=split(/ - /,$data[$i+2]);
($team1name,$team1score)=split(/ /,$team1);
($team2name,$team2score)=split(/ /,$team2);
if($team1score>$team2score){
$teamWon=$team1name;
$teamLost=$team2name;
}elsif($team1score<$team2score){
$teamWon=$team2name;
$teamLost=$team1name;
}else{
$teamWon="Draw";
$teamLost="Draw";
}
$sth2->execute();
while(@dateTeamWagerBet=$sth2->fetchrow_array()){
if($dateTeamWagerBet[0] eq $dateOfMatch){
if($teamWon eq $dateTeamWagerBet[1] && $dateTeamWagerBet[3] eq "Win"){
$success=$dbh->do("UPDATE $serverTabl set balance=$dateTeamWagerBet[2] WHERE date=$dateOfMatch AND team=$teamWon AND
balance is NULL");
}elsif($teamLost eq $dateTeamWagerBet[1] && $dateTeamWagerBet[3] eq "Loss"){
$success=$dbh->do("UPDATE $serverTabl set balance=$dateTeamWagerBet[2] WHERE date=$dateOfMatch AND team=$teamLost AND
balance is NULL");
}elsif(($teamWon eq $dateTeamWagerBet[1] || $teamLost eq $dateTeamWagerBet[1]) && $dateTeamWagerBet[3] eq "Draw"){
$success=$dbh->do("UPDATE $serverTabl set balance=$dateTeamWagerBet[2] WHERE date=$dateOfMatch AND
(team=$teamWon OR team=$teamLost) AND bet='Draw' AND balance is NULL");
}
}
}
}
}
}
$i++;
}
$sth3=$dbh->prepare("SELECT SUM(balance) FROM $serverTabl where accountid=$currentUserId");
$sth3->execute();
@row=$sth->fetchrow_array();
print"Your total balance is @row", br();
$correct=0;
$sth2->execute();
while(@dateTeamWagerBet=$sth2->fetchrow_array()){
foreach(@dateTeamWagerBet){
if($dateTeamWagerBet[4] ne ""){$correct++;}
}
}
$correct--;
print"you have predicted $correct correct matches up to date",br();
endHTML();
$sth3->finish();
$sth2->finish();
$dbh->disconnect();
}



sub storePredictions{
my($currentUserId,$currentUserLastName); my(@values);
$currentUserId=param("currentUserId");$currentUserLastName=param("currentUserLastName");
$dbh=DBI->connect("DBI:mysql:database=$serverDb;host=$serverName;port=$serverPort",$serverUser,$serverPass)
or die ("Cant connect to the database: ". DBI->errstr);
$Count=1;
my $sth = $dbh->prepare("INSERT INTO $serverTabl(accountid,date,team,wager,bet)
VALUES(?,?,?,?,?) WHERE date <> $values[3]");
startHTML();
do{
$values[0]=param("match$Count");
$values[1]=param("wager$Count");
$values[2]=param("bet$Count");
$values[3]=param("date$Count");
print "$sth->execute($currentUserId,$values[3],$values[0],$values[1],$values[2]);";


# $dbh->do(qq\insert into $serverTabl (accountid,date,team,wager,bet)
# values("$currentUserId","$values[3]","$values[0]","$values[1]","$values[2]") WHERE date != "$values[3]"\);
# $dbh->do(qq\INSERT INTO $serverTabl(accountid,date,team,wager,bet) VALUES(?,?,?,?,?) WHERE date <> ?\,
# undef,$currentUserId,$values[3],$values[0],$values[1],$values[2],$values[3]);
$Count++;
}while(param("match$Count"));
endHTML();
$dbh->disconnect;
}



sub predictionsResults{
my($currentUserId,$currentUserLastName);
$currentUserId=param("currentUserId");$currentUserLastName=param("currentUserLastName");
my(@values,@headings,@rows);
startHTML();
print startform({-action=>"",-method=>"POST"});
@headings = ('Team','Result','Wager');
@rows = th(\@headings);
$Count=1;
do{
$values[0]=param("match$Count");
$values[1]=param("matchwager$Count");
$values[2]=param("windrawloss$Count");
$values[3]=param("dateOfMatch$Count");
$values[3]=~ s/,//;
print hidden(-name=>"match$Count",-value=>"$values[0]"),hidden(-name=>"wager$Count",-value=>"$values[1]"),
hidden(-name=>"bet$Count",-value=>"$values[2]"),hidden(-name=>"date$Count",-value=>"$values[3]");
push(@rows,td([$values[0],$values[2],$values[1]]));
$Count++;
}while(param("match$Count"));
print table({-border=>"1",-width=>'25%'},caption(b('Here are your predictions.')),Tr(\@rows));
print br(),br(),"Is this correct?",br();
print checkbox(-name=>'correct',-value=>'yes',-label=>'Yes');
print checkbox(-name=>'correct',-value=>'no',-label=>'No');
print hidden(-name=>"currentUserId",-value=>"$currentUserId"),hidden(-name=>"currentUserLastName",-value=>"$currentUserLastName");
print submit(-name=>"predictionsResults",-value=>"predictionsResults",-label=>'submit'),end_form();
endHTML();
}

sub prediction{
my($currentUserId,$currentUserLastName);
$currentUserId=param("currentUserId");$currentUserLastName=param("currentUserLastName");
startHTML();
print h3("CFL predictions pool. Make your predictions.");
$date=`date`;
my @date=split(/ /,$date);
$"=" ";
print"Today is: @date", br();
$date[2]+=7;
print b("You can only make predictions up to: $date[1],$date[2]"),br(),br();
if($date=~/aug/i){
$useSchedule=$augustSchedule;
}elsif($date=~/sep/i){
$useSchedule=$septemberSchedule;
}elsif($date=~/oct/i){
$useSchedule=$octoberSchedule;
}elsif($date=~/nov/i){
$useSchedule=$novemberSchedule;
}
$content=get($useSchedule);
@date=split(/ /,$date);
$content=~ s/<.*?>//g;
$content=~ s/&nbsp;//g;
($temp,$content)=split(/tNov/,$content);
($content,$temp)=split(/Powered by/i,$content); $temp="";
$content=~ s/[^ A-Za-z0-9,:-]//g;
@data=split(/ {2,}/,$content);
shift(@data);
@data2=@data;
my($day,$month,$dayNum);
my $i=0; my($team1,$team2,$i2);
$Count=1;
print startform({-action=>"",-method=>"POST"});
foreach(@data){
if($data[$i]=~/[A-Z][a-z]{3,}, [A-Z][a-z]{3,} [0-9]{1,2}/){
($day,$month,$dayNum)=split(/ /,$data[$i]);
if($dayNum >= $date[2] && $dayNum <= ($date[2]+7)){
print hidden(-name=>"dateOfMatch$Count",-value=>"$data[$i]");
print"Match:$Count",br(),$data[$i],br(),"$data[$i+1]";
$data2[$i+1]=substr($data2[$i+1],0,index($data[$i+1],","));
($team1,$team2)=split(/ at /,$data2[$i+1]);
print popup_menu(-name=>"match$Count",-values=>[$team1,$team2]),br();
print "Wager:",popup_menu(-name=>"matchwager$Count",-values=>[qw(2 3 4 5)]),br();
print radio_group(-name=>"windrawloss$Count",-values=>['Win','Draw','Loss'],-linebreak=>'true'),br();
$Count++;
if($data[$i+2]=~ /.* at .*/){
print hidden(-name=>"dateOfMatch$Count",-value=>"$data[$i]");
print"Match:$Count",br(),$data[$i],br(),"$data[$i+2]";
$data2[$i+2]=substr($data2[$i+2],0,index($data[$i+2],","));
($team1,$team2)=split(/ at /,$data2[$i+2]);
print popup_menu(-name=>"match$Count",-values=>[$team1,$team2]),br();
print "Wager:",popup_menu(-name=>"matchwager$Count",-values=>[qw(2 3 4 5)]),br();
print radio_group(-name=>"windrawloss$Count",-values=>['Win','Draw','Loss'],-linebreak=>'true'),br();
$Count++;
}
}
}
$i++;
}
print hidden(-name=>"currentUserId",-value=>"$currentUserId"),hidden(-name=>"currentUserLastName",-value=>"$currentUserLastName");
print submit(-name=>"prediction",-value=>"prediction",-label=>'submit'),end_form();
}


sub welcome{
my($currentUserId,$currentUserLastName);
$currentUserId=param("currentUserId");$currentUserLastName=param("currentUserLastName");
startHTML();
print h4("Welcome user# $_[0]$currentUserId"),br(),"What would you like to do?";
print startform({-action=>"",-method=>"POST"});
print "Check your account? ",checkbox({-name=>'account',-value=>'account',-label=>''}),br();
print "Make predictions? ",checkbox({-name=>'predictions',-value=>'predictions',-label=>''}),br();
print hidden(-name=>"currentUserId",-value=>"$_[0]"),hidden(-name=>"currentUserLastName",-value=>"$_[1]");
print submit(-name=>"welcome",-value=>"welcome",-label=>'submit'),end_form();
endHTML();
}

sub login{
startHTML();
print h3("Login");
print "$specialError";
print startform({-action=>"",-method=>"POST"});
print textfield({-name=>"lname",-size=>"12",-value=>"$lastName"}),br();
print textfield({-name=>"id",-size=>"12",-value=>"$userID"}),br();
print submit(-name=>"LogIn",-value=>"LogIn"),end_form();
endHTML();
}

sub success{
startHTML();
print h3("You have successfully registered. Here is your information and Login ID."),br();
print "$firstName $lastName",br(),"$eMail",br();
print "Your ID# $randomNum",br();
print a({href=>"http://zenit.senecac.on.ca:16526/cgi-bin/assign2.cgi"},"Return to start page");
print endHTML();
}

sub validate{
$errors[0]="";$errors[1]="";$errors[2]="";$errors[3]="";$specialError="";
if($firstName!~/^[a-z]{2,}[ ]*[a-z]$/i){
$errors[0]="Only alphabetic characters, minimum two characters long";}
if($lastName!~/^[a-z]{2,}[ ]*[a-z]$/i){
$errors[1]="Only alphabetic characters, minimum two characters long";}
if($eMail!~/^[a-z:.~?=+&]{1,}@[a-z.]{1,}$/i){ #:/.~?=+&@
$errors[2]="E-mail field only allows the folloing characters: :/.~?=+&@";}
if($eMail=~/\.\./){
$errors[3]="Two consecutive periods are not allowed!";}
}


sub regForm{
startHTML();
print h1($specialError);
print startform({-action=>"",-method=>"POST"});
print table(TR(td("First Name:"),td(textfield({-name=>"fname",-size=>"12",-maxlength=>"12",-value=>"$firstName"})),td($errors[0])),
TR(td("Last Name:"),td(textfield({-name=>"lname",-size=>"12",-maxlength=>"12",-value=>"$lastName"})),td($errors[1])),
TR(td("E-Mail:"),td(textfield({-name=>"email",-size=>"24",-maxlength=>"24",-value=>"$eMail"})),td($errors[2],$errors[3])));
print hidden(-name=>'hidden',-value=>'register');
print submit(-name=>"regForm", -value=>"register");
print end_form();
endHTML();
}

sub firstPage{
my %labels = ('1'=>'I am a member. Sign In.','2'=>'Register');
startHTML();
print h1('Welcome to the Assign2 CFL Pool');
print startform({-action=>"",-method=>"POST"});
print checkbox_group(-name=>'firstPage',-values=>['1','2'],-labels=>\%labels,-linebreak=>'true');
print hidden(-name=>"hidden",-value=>"first");
print submit(-name=>'first',-value=>'first',-label=>'submit');
print end_form();
endHTML();
}

sub endHTML{
print end_html();
}

sub startHTML{
print header();
print start_html(-title=>'Assign2 Daniel');
}





brainStorm

FishMonger
08-15-2009, 01:47 AM
No, like this:

print "'INSERT INTO $serverTabl(accountid,date,team,wager,bet) VALUES($currentUserId,$values[3],$values[0],$values[1],$values[2]) WHERE date <> $values[3]'";

hackYourBrain
08-15-2009, 05:16 PM
huh.. by printing the above statement it would appear that the command being sent is incorrect. looks like the first variable is being interpolated but the rest are not.. including the one in the where clasue.. huh??

output


'INSERT INTO assign2(accountid,date,team,wager,bet) VALUES(52900,,,,) WHERE date <> '


why is that happeing?? im gona do some tests.. if you got any input fish please post...

Actually sorry.. i printed the above before i got my values[].. here is the real output and it looks correct



''INSERT INTO assign2(accountid,date,team,wager,bet) VALUES(52900,Saturday August 15,Montreal,5,Win) WHERE date <> Saturday August 15''

Whats the deall???

What if these records are being inserted for the first time and there are no records with a date in them.. would that prevent this command from being executed?? because the first time I run this there are no records.. but for the second time there will be and I want to make sure that no duplicated records are made.. the most easy way possible i could think of and that is to check if that date already exists in the table??


Thanks
Electron

FishMonger
08-15-2009, 05:36 PM
What is the data type for the date field?

Is it set as a varchar or date or datetime or ?

http://dev.mysql.com/doc/refman/5.0/en/data-types.html

FishMonger
08-15-2009, 06:19 PM
Try changing the where clause to this:

WHERE date is NULL or date <> $values[3]

hackYourBrain
08-15-2009, 06:59 PM
all my fields are character so as to avoid any problems... and I have given up on there where clause and decided to pull all the existing dates from the table compare them against the date of the record thats about to be inserted and based on that decide wether to insert it or not.. BUT I cant even get that right..i keep getting lots of duplication when it goes through this process.. can you see what is wrong with this logic??



$Count=1;
$sth=$dbh->prepare("SELECT date FROM $serverTabl");
do{
$sth->execute();
$values[0]=param("match$Count");
$values[1]=param("wager$Count");
$values[2]=param("bet$Count");
$values[3]=param("date$Count");
$flag=0;
while(@date=$sth->fetchrow_array()){
if($values[3] eq $date[0]){$flag=1;}
if($flag!=1){$dbh->do("INSERT INTO $serverTabl(accountid,date,team,wager,bet) VALUES(?,?,?,?,?)",
undef,$currentUserId,$values[3],$values[0],$values[1],$values[2]);}
}
$Count++;
}while(param("match$Count"));


i dont get it look good to me??

project 357652, industrial espionage and intelligence manipulation

hackYourBrain
08-15-2009, 07:19 PM
Never mind fish I found it.. and there was another problem and this is there were also situations where there are more then one game on the same date so I had to add another condition.. it works now.. thanks Fish for all your help

my whole function


sub storePredictions{
my($currentUserId,$currentUserLastName,$sth2); my(@values,@data);
$currentUserId=param("currentUserId");$currentUserLastName=param("currentUserLastName");
$dbh=DBI->connect("DBI:mysql:database=$serverDb;host=$serverName;port=$serverPort",$serverUser,$serverPass)
or die ("Cant connect to the database: ". DBI->errstr);
$Count=1;
$sth=$dbh->prepare("SELECT date,team FROM $serverTabl");
do{
$sth->execute();
$values[0]=param("match$Count");
$values[1]=param("wager$Count");
$values[2]=param("bet$Count");
$values[3]=param("date$Count");
$flag=0;
while(@data=$sth->fetchrow_array()){
if($values[3] eq $data[0] && $values[0] eq $data[1]){$flag=1;}
}
if($flag!=1){$dbh->do("INSERT INTO $serverTabl(accountid,date,team,wager,bet) VALUES(?,?,?,?,?)",
undef,$currentUserId,$values[3],$values[0],$values[1],$values[2]);}
$Count++;
}while(param("match$Count"));
$sth->finish();
$dbh->disconnect;
}




RobVanDamme

hackYourBrain
08-17-2009, 06:58 PM
Hey fish I cant post my final script cause it too big haha.. i get a message saying its over 20000 characters or something.. any ideas? Well I dont really care no more cause im done this course.. just waiting on marks now.. got killed on the final though.. this prof is insane.. thats all i have to say about that.. glad I never have to see him again.. also why dont you guys have a math forum.. im gona need that over the next 12 months.. and beyond.. its in relation to computer science and engineering soo.. how about you create one.. also where is the c++ and java..and C whats going on??


IneedBlood

bazz
08-17-2009, 11:15 PM
the java forum is here, or accessible from the forums index ;)

http://www.codingforums.com/forumdisplay.php?f=54

bazz



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum