andy
andy

Reputation: 459

How to add arrays together from form and add them to one field in the database?

I have a while loop display checkboxes with a value assigned to each checkbox:

<input type='checkbox' name='rep[]' value='$invoiceID'>Reference Number: $invoiceID<input type='hidden' name='weektotal[]' value='$weekTotal'>";

For example if there were 3 checkboxes they'd look like this:

[] Reference Number: 1 (hidden value 30)
[] Reference Number: 2 (hidden value 50)
[] Reference Number: 3 (hidden value 40)

No if a user selected all 3 checkboxes how do I add all 3 hidden values together to insert that result in a field in the database (so the value would be 120). Or if the user selected the first 2 (so the value would be 80). I have tried this on the process page just before the INSERT statement:

$totalweek = array_sum($_POST['weektotal']);

And then use $totalweek in the VALUE for the insert.

This seemed to work but when I select the first one or the second checkbox on their own then it provides a result as if they were all being added up?

What is the correct way to do this?

Upvotes: 0

Views: 38

Answers (1)

undefined_variable
undefined_variable

Reputation: 6218

On the process page use following code:

$my_var = $_POST['rep'];
$var = $_POST['weektotal'];
$expense = $_POST['expensetotal'];
$total=0;
for($i=0;$i<sizeof($my_var);$i++){
$total=$total+$var[$i];
$exp = $exp+$expense[$i];
}
$grand_total = $total+$exp;

Upvotes: 1

Related Questions