?
Solved

Perl to store value to MySQL

Posted on 2009-04-16
14
Medium Priority
?
460 Views
Last Modified: 2012-08-14
Hey I have this Perl .cgi script. When it runs, you have to enter some information, and it then calculates your total energy expenditure (TEE) minus 20%. What I would like to do is to get that piece of information into a row together with the username of the one (Table: ett, rows: $HB_minus_20 (that is what it's called in the script, and username), who have signed on, so I will be able to read that information later without them having to enter it into that cgi script everytime they enter my homepage.
How would I do that? I am not good at Perl-scripting at all yet though.

I have 2 fields in my database-table, one called "kcal" and the other called "username"
I already have DBI and DBI::MySQL installed!

I assume it would look something like this:

"use strict;
use DBI;
 
my $dbh = DBI->connect("DBI:mysql:databasename;localhost",
                       "dbusername", "dbpassword", {'RaiseError' => 1}
);
 
my $sth = $dbh->prepare("INSERT INTO tee; kcal, username VALUES ?,?");
$sth->execute(1, $HB_minus_20, $session_['username']);"


Please help me!! Thanks :)
0
Comment
Question by:MisterHamper
  • 8
  • 4
  • 2
14 Comments
 

Author Comment

by:MisterHamper
ID: 24161043
Here is the script I am talking to

It is at line 298, that $HB_minus_20 is, and at line 306 it gets printed on the page.

I can elaborate, if you do not get what it is I'm saying :)
#!/usr/bin/perl
 
$text_color = "000000";
$page_background_color = "FFFFF0";
$page_links_color = "0000FF";
$page_active_links_color = "FF0000";
$page_visited_links_color = "0000FF";
$table_background_color= "F4E3C8";
$table_cell_color= "FFFFF0";
 
 
$header = qq[ 
<!-- Begin HTML header -->
<html><head><title>MetaboCalc v1.0 
</title></head><body bgcolor=#$page_background_color
text=#$text_color link=#$page_links_color 
vlink=#$page_visited_links_color 
alink=#$page_active_links_color>
<!-- End HTML header -->
];
 
 
$footer = qq[
<!-- Begin HTML footer -->
</center></body></html>
<!-- End HTML footer -->
];
 
 
$default_weight = "p"; 
 
 
$default_height = "i"; 
 
 
 
$notes = qq[
<!-- Begin HB Notes -->
<center><b>About Caloric Needs Calculation</b></center>
<br><br>
This calculator uses what is called the "Harris-Benedict Formula" to 
determine your daily calorie needs. There are a few things that are
important to remember about this formula. First, the formula was
devised many years ago, and has in recent years been determined to 
have up to a 20% error rate, depending upon the percentage of body fat
and other variables. (For this reason, the calculator shows plus and minus
5% and 20% so you can get an idea of the range.)
<br><br>
Secondly, the modification for your "lifestyle" (sedentary vs. moderately
active and so forth) is really a bit of a guess. "Sedentary" is "little or
no exercise" and you can imagine that there can be quite a bit of difference
between "little" and "no" exercise.
<br><br>
Weight loss cannot, unfortunately, be boiled down into an exact number.
All this can do is give you an idea of a potential range. Chances are good,
however, that if you limit your intake to the lower end of the spectrum,
you may be able to lose weight, but different people have different
metabolisms and so you may need fewer or more calories. 
<br><br>
Calculation of your "Basal Metabolic Rate" (or "Resting Metabolic Rate" as it's
sometimes called) is only one tool in your fitness arsenal. 
<br><br>
<a href="" onClick="self.close()">--Close Window--</a>
<!-- End HB Notes -->
];
 
 
$bmr_notes = qq[
<!-- Begin BMR Notes -->
<center><b>About BMR (Basal Metabolic Rate)</b></center><br><br>
"Basal Metabolic Rate" (sometimes also called "Resting Metabolic Rate")
or BMR is an approximate calculation of how many calories you would need
to maintain your current weight if you did nothing but stayed in bed all
day. This calculation is really only accurate for a certain percentage
of people, because your actual BMR depends on other things such as body
fat percentage, etc. For this reason, we also show BMR at plus or minus
20 percent, so you can get a better idea of the range.
<br><br>
When computed with your "lifestyle" number, this gives your overall 
calorie needs in a given day. 
<br><br>
<a href="" onClick="self.close()">--Close Window--</a>
<!-- End BMR Notes -->
];
 
$lifestyle_notes = qq[
<!-- Begin Lifestyle Notes -->
<b>About the Lifestyle Selection</b><br><br>
The lifestyle selections are a bit vague, but here are some approximations
that may help you choose.<br>
<table border=1 cellspacing=0>
<tr><td>Bed-Bound</td>
 <td>If you stay in bed all day for health or other reasons, choose this
	selection.</td></tr>
<tr><td>Sedentary</td>
 <td>This selection would be for someone with a "desk job" who does not
 exercise at all.</td></tr>
<tr><td>Lightly Active</td>
 <td>If you do light exercise 1 - 3 days per week, this selection may be
 appropriate for you.</td></tr>
<tr><td>Moderately Active</td>
 <td>If you do moderate exercise 3 - 5 days per week, this selection may be
 appropriate for you.</td></tr>
<tr><td>Active</td>
 <td>Usually, if you have a physical job (loading boxes, warehouse, delivery)
 and do moderate to strenous exercise 6 - 7 days per week, try this selection.
 </td></tr>
<tr><td>Very Active</td>
 <td>For people who are exercising or moving most of the time. For example, 
 loading boxes in a warehouse plus several hours of hard exercise or 
 sports 6 - 7 days per week, cross training, etc. Athletes and bodybuilders 
 often fall into this category.
 </td></tr>
</table>
<br><br>
<a href="" onClick="self.close()">--Close Window--</a>
<!-- End Lifestyle Notes -->
 
];
 
$bmi_notes = qq[
<!-- Begin BMI Notes -->
<center><b>About Body Mass Index</b></center>
<br><br>
It's important to realize that BMI is not the most accurate determination
of whether or not you are at an unhealthy weight. For example, if you are
extremely muscular, your BMI may show as "Overweight" or even "Obese,"
when you're not. By the same token, if you are a "Normal" BMI, but have
a very high body fat percentage, you may have the same health risks as
someone with an "Obese" BMI.
<br><br>
BMI or "Body Mass Index" is based on the following formula:
<br><br>
<blockquote>
	<table border=0>
	<tr>
	  <td rowspan=3 valign=center>
		<font size="+6">(</font>
	  </td>
	  <td align=center> Weight in pounds </td>
	  <td rowspan=3 valign=center> <font size="+6">)</font> </td>
	  <td rowspan=3 valign=center>&nbsp;*&nbsp;703 </td>
	  </tr>
	 <tr>
	   <td align=center>______________</td>
	 </tr>
	 <tr>
	   <td align=center>Height in inches<sup>2</sup></td>
	</table> 
 
</blockquote>
 
BMI is only one tool in your health arsenal. Body fat percentage is a much
better predictor of health risks than the ratio of your height to your
weight.
<br><br>
<a href="" onClick="self.close()">--Close Window--</a>
<!-- End BMI Notes -->
 
];
 
 
$about_hb_height = "400";
 
 
$about_hb_width = "300";
 
 
 
 
 
 
 
 
%data = &parse_form_data();
 
 
print "Content-type: text/html\n\n";
 
 
 
$footer = "<hr><font size=-2><a href=http://www.tesol.net/scripts/>
	   Powered by MetaboCalc v1.0
	   </a></font><br>$footer";
 
 
#################################################################
 
# If it's one of the popup window links that people are clicking on,
# we're just going to print out whatever explanation there is, and exit.
if($data{'FA'} eq "AboutHB"){ &print_explanation($notes); }
if($data{'FA'} eq "AboutBMR"){ &print_explanation($bmr_notes); }
if($data{'FA'} eq "AboutBMI"){ &print_explanation($bmi_notes); }
if($data{'FA'} eq "AboutLifestyle"){ &print_explanation($lifestyle_notes); }
 
# If not, then we're going to print the whole form and so forth. First,
# print our HTML for the top of the page.
print $header;
 
# Now, figure out whether they chose kilos/centimeters or pounds/inches.
# They could also choose pounds/centimeters, or kilos/inches. We will
# convert if necessary. :-)
$kilos_or_pounds = $data{'wt'};
$centimeters_or_inches = $data{'ht'};
 
# If weight is not a number at all, or if it is blank, or if it
# is less than or equal to zero, do the error.
$weight = $data{'weight'};
if($weight * 1 ne $weight || $weight eq "" || $weight <= 0){
	$errweight = "<font color=\"#FF0000\"><b>*</b></font>";
	$no_calc = 1;
	}
# Same for height.
$height = $data{'height'};
if($height * 1 ne $height || $height eq "" || $height <=0 ){
	$errheight = "<font color=\"#FF0000\"><b>*</b></font>";
	$no_calc = 1;
	}
# Same for age, except we also don't allow ages over 120.  
# My apologies in advance to anyone over the age of 120
# attempting to use this calculator.
$age = $data{'age'};
if($age == 0 || $age eq "" || $age > 120 | $age < 0){
	$errage = "<font color=\"#FF0000\"><b>*</b></font>";
	$no_calc = 1;
	}
# If gender is not "m" or "f", do an error.
$gender = $data{'gender'};
if($gender ne "m" && $gender ne "f"){
	$errgender = "<font color=\"#FF0000\"><b>*</b></font>";
	$no_calc = 1;
	}
 
# If their lifestyle is "bed bound," or anything but the general
# lifestyle multiples, we just call it the same as the BMR. 
# I don't think you're really supposed to do this with Harris-Benedict
# calculations, but I have, in the past, wanted to do the base calculation
# so therefore everyone gets to.
$lifestyle = $data{'lifestyle'};
if($lifestyle != 1.2 &&
   $lifestyle != 1.375 &&
   $lifestyle != 1.55 &&
   $lifestyle != 1.725 &&
   $lifestyle != 1.9){
	$lifestyle = 1;
	}
 
# Set a variable to tell us it's okay to do the calculations if we
# didn't hit one of our errors above.
if($no_calc != 1){ $do_calc = 1; }
 
# We're just going to do the formula in pounds and inches, regardless.
# So, if they entered it in kilos or centimeters, we need to convert.
# Since the answers are ratios, the numbers will be the same whichever
# we use.
if($kilos_or_pounds eq "k"){
	$weight = &convert_to_pounds($weight);
	}
else {
	$weight = $weight;
	}
if($centimeters_or_inches eq "c"){
	$height = &convert_to_inches($height);
	}
else {
	$height = $height;
	}
 
# There are two formulae for BMR: one for men and one for women. If they
# entered female, do the one for women. The sprintf() thing tells it
# to display as a number with no decimal places.
if($gender eq "f" && $do_calc == 1){
	# This is the female version of the formula
	$BMR = sprintf("%d", 655 + (4.35 * $weight) + (4.7 * $height) - (4.7 * $age));
	}
# Otherwise, do the one for men.
elsif($gender eq "m" && $do_calc == 1){
	# This is the male version of the formula
	$BMR = sprintf("%d", 66 + (6.23 * $weight) + (12.7 * $height) - (6.8 * $age));
 
	}
# If they're not male or female, or there was another error above,
# then it's No BMR for You!
else {
	$BMR = 0;
	}
 
# We're also going to do some little calcs for plus and minus 5 and 20% so
# people can see a range. sprintf("%d", some number) makes it chop off any
# decimal places and just show a whole number.
 
	$HB_main = sprintf("%d",$BMR * $lifestyle);
	$BMR_plus_20 = sprintf("%d", $BMR + ($BMR * 0.2));
	$HB_plus_20 = sprintf("%d",$BMR_plus_20 * $lifestyle);
	$BMR_plus_5 = sprintf("%d",$BMR + ($BMR * 0.05));
	$HB_plus_5 = sprintf("%d",$BMR_plus_5 * $lifestyle);
	$BMR_minus_20 = sprintf("%d",$BMR - ($BMR * 0.2));
	$HB_minus_20 = sprintf("%d",$BMR_minus_20 * $lifestyle);
	$HB = qq[<table border=0><tr><td colspan=2><b>Your daily kcal:</b>] .
	      qq[<a href="" onClick="window.open('$cgi_url?FA=AboutHB',] .
	      qq['AboutHB','width=$about_hb_width,height=$about_hb_height,] .
	      qq[toolbar=no,scrollbars=yes,resizable=yes,status=no,] .
	      qq[directories=no,menubar=no,location=no'); return false;">(?)] .
	      qq[</a></td></tr>
	<tr>
	<td>Minus 20%:</td><td>$HB_minus_20</td>
	</tr>
	</table>
	
	];
# Now everything is in pounds and inches, since HB is relative anyway.
# Calculate BMI because the code was already stolen from SFEBMIcalc and
# what the heck -- give people more info! 
if($weight > 0 && $height > 0){
	$BMI = sprintf("%.02f", ( $weight / ($height * $height)) * 703);
	}
else {
	$BMI = "?";
	}
 
# The get_form subroutine pretty much prints out the form, saves whatever
# they entered, etc.
print &get_form;
 
 
print qq[
	<table border=0 width="100%">
	 <tr>
	  <td>
	];
print "$HB" if $HB;
print "<b>Your calorie needs are unknown: calculate them!</b>" if !$HB;
print qq[
	</td><td align="right" valign="bottom">
	];
print $about_hb_link;
print qq[
	</td></tr></table>
	];
print $footer;
exit();
 
sub get_form {
 
$form = "<table border=1><tr><td>
	<table border=0>
	 <tr><td>
		<table border=0>
         <tr><td valign=top>
	<center><b>How many calories do you need?</b></center><br>
	<center><i>(Based on the Harris-Benedict formula)</i></center><br>
	<form action=$cgi_url method=POST>
        <table border=0>
	<tr><th align=right>$errweight
        Your weight:
	</th>
	<td bgcolor=#$table_cell_color>
	  <input type=text name=weight size=5 value=\"$data{'weight'}\">
	<select name=\"wt\">";
	if($data{'wt'} eq "k" || $default_weight eq "k"){ 
		$kilock = " SELECTED"; $pck = ""; 
		}
	elsif($data{'wt'} eq "p" || $default_weight eq "p"){ 
		$kilock = ""; $pck = " SELECTED"; 
		}
	$form .= "
	<option value=\"p\"$pck>Pounds</option>
	<option value=\"k\"$kilock>Kilograms</option>
	</select>
	</td>
	</tr>
	<tr>
	 <th align=right>$errheight
	  Your Height:
	 </th>
	 <td bgcolor=#$table_cell_color>
	   <input type=text name=height size=5 value=\"$data{'height'}\">
	<select name=\"ht\">";
	if($data{'ht'} eq "c" || $default_height eq "c"){ 
		$kilock = " SELECTED"; $pck = ""; 
		}
	elsif($data{'ht'} eq "i" || $default_height eq "i"){ 
		$kilock = ""; $pck = " SELECTED"; 
		}
	$form .= "
	<option value=\"i\"$pck>Inches</option>
	<option value=\"c\"$kilock>Centimeter</option>
	</select>
	 </td>
	</tr>
	<tr>
	 <th align=right>$errage
	  Your Age (in Years):
	 </th>
	 <td bgcolor=#$table_cell_color>
	<input type=text size=\"5\" name=\"age\" value=\"$data{'age'}\">
	 </td>
	</tr>
	<tr>
	 <th align=right>$errgender
	  Your Gender:
	 </th>
	 <td bgcolor=#$table_cell_color>
	<select name=\"gender\">";
	if($data{'gender'} eq "m"){
		$maleck = " SELECTED"; $femaleck = ""; 
		}
	elsif($data{'gender'} eq "f"){
		$maleck = ""; $femaleck = " SELECTED"; 
		}
	$form .= "
	<option value=\"\">-- Select Gender--</option>
	<option value=\"m\"$maleck>Male</option>
	<option value=\"f\"$femaleck>Female</option>
	</select>
	 </td>
	</tr>
	<tr>
	 <th align=right>$errlifestyle
	  Your Lifestyle:
	 </th>
	 <td bgcolor=#$table_cell_color>
	<select name=\"lifestyle\">";
	if($data{'lifestyle'} eq "1.2"){
		$zero = ""; $one = " SELECTED"; $two = ""; 
		$three = ""; $four = ""; $five = ""; 
		}
	elsif($data{'lifestyle'} eq "1.375"){
		$zero = ""; $one = ""; $two = " SELECTED"; 
		$three = ""; $four = ""; $five = ""; 
		}
	elsif($data{'lifestyle'} eq "1.55"){
		$zero = ""; $one = ""; $two = ""; 
		$three = " SELECTED"; $four = ""; $five = ""; 
		}
	elsif($data{'lifestyle'} eq "1.725"){
		$zero = ""; $one = ""; $two = ""; 
		$three = ""; $four = " SELECTED"; $five = ""; 
		}
	elsif($data{'lifestyle'} eq "1.9"){
		$zero = ""; $one = ""; $two = ""; 
		$three = ""; $four = ""; $five = " SELECTED"; 
		}
	else {
		$zero = " SELECTED"; $one = ""; $two = ""; 
		$three = ""; $four = ""; $five = ""; 
		}
	$form .= "
	<option value=\"1\"$zero>Bed-Bound</option>
	<option value=\"1.2\"$one>Sedentary</option>
	<option value=\"1.375\"$two>Lightly Active</option>
	<option value=\"1.55\"$three>Moderately Active</option>
	<option value=\"1.725\"$four>Active</option>
	<option value=\"1.9\"$five>Very Active</option></select>
	<a href=\"\" onClick=\"window.open('$cgi_url?FA=AboutLifestyle','AboutLifestyle','width=$about_hb_width,height=$about_hb_height,toolbar=no,scrollbars=yes,resizable=yes,status=no,directories=no,menubar=no,location=no'); return false;\">(?)</a></td></tr>
	 </td>
	</tr>
	<tr>
	 <td>
	 </td>
	 <td bgcolor=#$table_cell_color>
	  <input type=submit value=Submit>&nbsp;<input 
	  type=reset value=Reset>
	 </td>
	 </tr></form></table></td>
	<td>
	  <table border=0 cellpadding=0 cellspacing=1><tr>
		<td bgcolor=\"$table_background_color\">
	  <table border=0 cellpadding=3 cellspacing=2>
 
	
		</table>
		</td></tr></table></td></tr></table></td></tr></table>
		";
  $form;
}
 
sub parse_form_data {
    my($string,%data,@data);
    
    # get data
    if ($ENV{'REQUEST_METHOD'} eq 'GET') {
        $_ = $string = $ENV{'QUERY_STRING'};
	tr/\"~;/_/;
	$string = $_;
 
    }				
    else { read(STDIN, $string, $ENV{'CONTENT_LENGTH'});
        $_ = $string;
	$OK_CHARS='a-zA-Z0-9=&%\n\/_\-\.@';
	tr/\"~;/_/;
	$string = $_;
	   }
 
    # split data into name=value pairs
    @data = split(/&/, $string);
   
    # split into name=value pairs in associative array
    foreach (@data) {
	split(/=/, $_);
	$_[0] =~ s/\+/ /g; # plus to space
	$_[0] =~ s/%(..)/pack("c", hex($1))/ge; # hex to alphanumeric
	$data{"$_[0]"} = $_[1];
    }
 
    # translate special characters
    foreach (keys %data) {
	$data{"$_"} =~ s/\+/ /g; # plus to space
	$data{"$_"} =~ s/%(..)/pack("c", hex($1))/ge; # hex to alphanumeric
    }
 
    %data;			# return associative array of name=value
}
 
sub convert_to_pounds {
 
 my($kilos) = $_[0];
 my($pounds) = $kilos * 2.20462262;
 $pounds;
}
 
sub convert_to_inches {
 
 my($centimeters) = $_[0];
 my($inches) = $centimeters * 0.393700787;
 $inches;
 
}
 
sub print_explanation {
 
 print "$_[0]";
 exit();
 
}

Open in new window

0
 
LVL 1

Expert Comment

by:Bbouch
ID: 24161207
I'm not a perl Guru, but I don't believe you need a prepare for an insert statement

Try:

my $userName = $session_['username'];
$dbh->do("Insert into tee (kcal, username ) values('$HB_minus_20', '$userName' ");



and see if that does what you are looking for.  You should be able to do it without setting the extra variavble, but for readability in the example I added it in there.
0
 

Author Comment

by:MisterHamper
ID: 24161238
Ahh thank you! Where would I place it in my script? At line 309?
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:MisterHamper
ID: 24161391
By the way, it would also need to connect to my MySQL database. How would I do that in Perl?

In PHP I do it like this
session_start();
include ('config.php');
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

$connection = mysql_connect($server, $dbusername, $dbpassword) or die(mysql_error());

$db = mysql_select_db($db_name,$connection) or die(mysql_error());

But I don't know much about Perl sadly :( Could you please help me with that? :) Thanks!
0
 
LVL 1

Assisted Solution

by:Bbouch
Bbouch earned 800 total points
ID: 24161403
You still need to connect to the database (as outlined in your other post "Get Perl to store a number in my MySQL table?")

A tthe beginning of your script:
use DBI;

After line 309:
my $userName = $session_['username'];
my $dbh = DBI->connect("DBI:mysql:databasename;localhost",
                       "dbusername", "dbpassword", {'RaiseError' => 1}
);
$dbh->do("Insert into tee (kcal, username ) values('$HB_minus_20', '$userName' ");
$dbh->disconnect();
0
 

Author Comment

by:MisterHamper
ID: 24161468
I couldn't find my other post again at all, so I thought it had been deleted! But thanks! I found it! I just read through your links, and tried to make it connect to my database

my $dsn = 'dbi:mysql:MY DB NAME:localhost:3306';
 
my $user = 'MY DB USER';
my $pass = 'MY DB PASS';
 
my $dbh = DBI->connect($dsn, $user, $pass)
 or die "Cant connect to the DB: $DBI::errstr\n";

and placed it right below "#!/usr/bin/perl", but it gives me an 500 Error. I also remembered to upload it in Ascii and chmod 755
0
 
LVL 39

Accepted Solution

by:
Adam314 earned 1200 total points
ID: 24161720
For the 500 error, you will need to look in your error log.  You could also add this right after your #! line:
    use CGI::Carp 'fatalsToBrowser';
This will cause more detailed error messages to be displayed to your browser.

For the insert, you can use a prepare, or not.  If you are doing multiple inserts, using the prepare will be faster.  If you are only doing 1, it won't matter.

Either way, you should use placeholders, to avoid any possible quoting problems:
    $dbh->do('INSERT INTO tee (kcal, username) VALUES (?, ?)', $HB_minus_20, $userName);
Or
    my $sth = $dbh->prepare('INSERT INTO tee (kcal, username) VALUES (?, ?)');
    $sth->execute($HB_minus_20, $userName);


0
 

Author Comment

by:MisterHamper
ID: 24161842
Oh I see, thanks!

Well it gives me this error:
"Can't locate object method "connect" via package "DBI" at metabocalc.cgi line 16."

#!/usr/bin/perl
use CGI::Carp 'fatalsToBrowser';

# set the data source name
# format: dbi:db type:db name:host:port
# mysqls default port is 3306
# if you are running mysql on another host or port,
#    you must change it
my $dsn = 'dbi:mysql:MYDBNAME:localhost:3306';
 
# set the user and password
my $user = 'MYDBUSER';
my $pass = 'MYDBPASS';
 
# now connect and get a database handle  
my $dbh = DBI->connect($dsn, $user, $pass) //THIS IS LINE 16
 or die "Cant connect to the DB: $DBI::errstr\n";

Is it written wrong? Thanks for the help
0
 
LVL 39

Expert Comment

by:Adam314
ID: 24161856
You didn't load the DBI module.  Add this after line 2 (after the "use CGI::Carp" line):
    use DBI;
0
 

Author Comment

by:MisterHamper
ID: 24161944
Ahh yes that was correct. The page loads now and seems to work great, except the part where it should store the $HB_minus_20 in the database, once you click "Submit."
Instead, my page looks shows this at the bottom
"Your daily kcal:(?)
Minus 20%:      2011
my = ; my DBI::db=HASH(0x7e3870) = DBI->connect("DBI:mysql:databasename;localhost", "dbusername", "dbpassword", {'RaiseError' => 1} ); my = DBI::db=HASH(0x7e3870)->prepare('INSERT INTO tee (kcal, username) VALUES (?, ?)'); ->execute(2011, ); DBI::db=HASH(0x7e3870)->disconnect(); "

I think the code here should be enclosed in () or [] or something. I am not sure how it that would work in Perl :)
...
	<tr>
	<td>Minus 20%:</td><td>$HB_minus_20</td>
	</tr>
	</table>
	
 
my $userName = $session_['username'];
my $dbh = DBI->connect("DBI:mysql:databasename;localhost",
                       "dbusername", "dbpassword", {'RaiseError' => 1}
);
    my $sth = $dbh->prepare('INSERT INTO tee (kcal, username) VALUES (?, ?)');
    $sth->execute($HB_minus_20, $userName);
    $dbh->disconnect();
	
	];
...

Open in new window

0
 
LVL 39

Expert Comment

by:Adam314
ID: 24161989
You should use one of the HTML template module to make the handling of HTML and perl code easier: HTML::Template or Template Toolkit.

But continuing this way, the new code should have been added after the closing square bracket on line 310.
0
 

Author Comment

by:MisterHamper
ID: 24162215
Thanks! It seems we are getting pretty close!

It gives me this error now;
"Software error:

DBD::mysql::st execute failed: Column 'username' cannot be null at metabocalc.cgi line 515."

I think what it needs is to know what user is signed on. On my other pages, I have a login-system, where it redirects you to a login-page if you have not signed on. Fx my index top looks like this

<?php

//prevents caching
header("Expires: Sat, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: post-check=0, pre-check=0",false);
session_cache_limiter();
session_start();

require('config.php');

require('functions.php');

//this is group name or username of the group or person that you wish to allow access to
// - please be advise that the Administrators Groups has access to all pages.
if (allow_access(Users) != "yes")
{
include ('no_access.html');
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<link rel="shortcut icon" href="favicon.ico">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>

But I can't just add that PHP-code to my .cgi script, can I?
0
 
LVL 39

Expert Comment

by:Adam314
ID: 24162410
Do,you can't just add php code, it won't work.  I don't work with php, so don't know much about it.

The PHP::Session module might help:
    http://search.cpan.org/~miyagawa/PHP-Session-0.27/lib/PHP/Session.pm
0
 

Author Comment

by:MisterHamper
ID: 24162827
Oh I see! Thanks for your help, everyone! I think I got the help I needed! Have a nice day!
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

On Microsoft Windows, if  when you click or type the name of a .pl file, you get an error "is not recognized as an internal or external command, operable program or batch file", then this means you do not have the .pl file extension associated with …
In the distant past (last year) I hacked together a little toy that would allow a couple of Manager types to query, preview, and extract data from a number of MongoDB instances, to their tool of choice: Excel (http://dilbert.com/strips/comic/2007-08…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Six Sigma Control Plans
Suggested Courses

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question