user1551672
user1551672

Reputation: 119

Getting multiple values of checkbox from a loop

while($row = mysql_fetch_array($result)){       
echo '<tr>
        <td>'.$row[0].'</td>
        <td>'.$row[1].'</td>
        <td>'.$row[2].'</td>';
        $price=$row['price'];
        echo "<td><input type='checkbox' name='er' value='$price'></td>";
echo "</tr>";

PHP file

 <?php
       $ercharge=$_POST['er'];
       echo $ercharge;
?>

I have a list of charges that was from a mysql table and it has a checkbox for each item so it would compute the sum. The above code works and it outputs the price of the checked item. The problem is, it's only one item. When multiple items are checked, only one is outputted.

Upvotes: 1

Views: 1711

Answers (4)

Ja͢ck
Ja͢ck

Reputation: 173552

The input box name should reflect that it's an array by adding the [] suffix:

echo '<td><input type="checkbox" name="er[]" value=" . htmlspecialchars($row['price']) . "></td>';

Then, to process the sum after making sure the input validates as proper values:

if ($ers = filter_input(INPUT_POST, 'er', FILTER_VALIDATE_FLOAT, FILTER_FORCE_ARRAY)) {
    $ercharge = array_sum($ers);
}

Upvotes: 0

Toretto
Toretto

Reputation: 4711

Try this it may help you

echo "<td><input type='checkbox' name='er[]' value='$price'></td>";
echo "</tr>";

$recharge=$_POST['er'];

foreach($recharge as $val)
{
     echo $val;
}

Or you can just do this without using foreach

$arra_val=array_sum($recharge);

you just need to put the value in to some variable and echo it.

Upvotes: 1

Michoel
Michoel

Reputation: 874

If you want to pass a number of elements in an array append the name with square brackets, so it would be:

echo "<td><input type='checkbox' name='er[]' value='$price'></td>";

And the result of $_POST['er'] would be an array of all of the checkbox values.

Upvotes: 0

Kickstart
Kickstart

Reputation: 21513

Try this:-

echo "<td><input type='checkbox' name='er[]' value='$price'></td>";

Upvotes: 1

Related Questions