Page 1 of 1

Embedding variables in $_POST[''] commands

Posted: Tue Jul 26, 2005 11:00 am
by bwv2
I'm having a bit of a head scratcher here, and wanted to see if one of you experienced PHP guys can help a mere infant of a PHP guy such as myself.

My problem is that I want to have a loop that will assign $_SESSION values by pulling $_POST values. I'm trying to loop through each with a FOR lop, but it won't recognize my embedded variables. Below is my code, and I'm just getting 0 for my $_SESSION values. Is there something wrong with my syntax?

Code: Select all

for($i=0; $i<=15; $i++){
     $_SESSION['q.$i'] = $_POST['quant_.$i']; 
	$_SESSION['w.$i'] = $_POST['watts_.$i']; 
	$_SESSION['summ.$i'] = $_POST['summ_.$i']; 
	$_SESSION['wint.$i'] = $_POST['wint_.$i'];
}

Posted: Tue Jul 26, 2005 11:03 am
by anjanesh
For PHP to recognize embedded variables you'll need to use double quotes (") instead of single ones (').

Code: Select all

$_SESSION["q.$i"] = $_POST["quant_.$i"]; 
$_SESSION["w.$i"] = $_POST["watts_.$i"];
$_SESSION["summ.$i"] = $_POST["summ_.$i"];
$_SESSION["wint.$i"] = $_POST["wint_.$i"];

Posted: Tue Jul 26, 2005 11:59 am
by bwv2
I tried what you suggested but am still not getting any output. I have narrowed my problem and rewritten my code a little, so have a look at the new code:

Code: Select all

for($i=0; $i<=15; $i++){
	$_SESSION['summerKwh']=$_SESSION['summerKwh'] + $_POST["quant_.$i"]*($_POST["watts_.$i"]/1000)*($_POST["summ_.$i"]);
	$_SESSION['winterKwh']=$_SESSION['winterKwh'] + $_POST["quant_.$i"]*($_POST["watts_.$i"]/1000)*($_POST["wint_.$i"]);
	}
Now I put in a PRINT command within the code to see what values were being output for the $_POST["quant_.$i"] type calls. I got no output for these. Though, when I manually wrote the number like $_POST[quant_1], I did get the correct output.

Is there some type of code of conduct for embedding variables within global arrays that I don't know about? Any help would be appreciated.

Posted: Tue Jul 26, 2005 12:04 pm
by bwv2
Okay, disregard the need to reply to me. I messed with it some more and figured it out. In case anyone else needs the help, here's what I did:

Code: Select all

for($i=0; $i<=15; $i++){    
     $_SESSION['summerKwh']=$_SESSION['summerKwh'] + $_POST["quant_".$i.""]*($_POST["watts_".$i.""]/1000)*($_POST["summ_".$i.""]);    
     $_SESSION['winterKwh']=$_SESSION['winterKwh'] + $_POST["quant_".$i.""]*($_POST["watts_".$i.""]/1000)*($_POST["wint_".$i.""]);    
}