php sum values of form check boxes when checked -


i have form in php displays checkboxes. these checkboxes associated numerical value populated mysql. i'm looking add values of each checkbox, if box checked.

the problem running no matter boxes have checked, value first checkbox(es) returned. example, if there 5 total checkboxes , select bottom 2, returned sum 2 top boxes not bottom boxes. seems php code knows boxes being checked, doesn't know boxes being checked.

here form code

echo "<input type=\"hidden\" name=\"id[]\" value=\"".$row['id']."\" />"; echo "<tr><td>&nbsp;<input type=\"checkbox\" name=\"checked[]\" value=\"y\"></td>"; echo "<input type=\"hidden\" name=\"amount[]\" value=\"".$row['amount']."\" />"; 

and here post

if('post' == $_server['request_method']) { $amt = 0; $totamt = 0; foreach($_post['id'] $i => $id) {  $id = mysql_real_escape_string($id);   $checked = mysql_real_escape_string($_post['checked'][$i]);   $amt = mysql_real_escape_string($_post['amount'][$i]);  if ($checked == "y") { $totamt = $totamt + $amt; $amt = 0; }  } echo $totamt; } 

thank help.

the checkboxes sent form ones checked, , array indexes start 0 no matter ones are. there's no correspondence between indexes of checkboxes , indexes of hidden fields. there few ways deal this.

one way put explicit indexes in checkbox names:

echo "<tr><td>&nbsp;<input type=\"checkbox\" name=\"checked[".$row['id']."]\" value=\"y\"></td>"; echo "<input type=\"hidden\" name=\"amount[".$row['id']."]\" value=\"".$row['amount']."\" />"; 

then can add up:

$totamt += $_post['amount'][$_post['checked'][$i]]; 

another way put amounts directly in value of checkboxes, instead of useless y value:

echo "<tr><td>&nbsp;<input type=\"checkbox\" name=\"checked[]\" value=\"".$row['amount']."\" /></td>"; 

then do:

$totamt += $_post['checked'][$i]; 

a third way put explicit indexes in names of fields, instead of letting php assign them when form submitted:

echo "<input type=\"hidden\" name=\"id[".$i."]\" value=\"".$row['id']."\" />"; echo "<tr><td>&nbsp;<input type=\"checkbox\" name=\"checked[".$i."]\" value=\"y\"></td>"; echo "<input type=\"hidden\" name=\"amount[".$i."]\" value=\"".$row['amount']."\" />"; 

where $i variable increment you're generating form. make indexes work way form code expects.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -