Home > Back-end >  Issue getting PHP to accept checkbox selections
Issue getting PHP to accept checkbox selections

Time:11-23

I am trying to get PHP to accept the information from a series of checkboxes in a form but when I try to verify/use said data to manipulate other data it isn't there.

<p><input type="checkbox" name="toppings[]" value="xchese"/>Extra Cheese</p>
<p><input type="checkbox" name="toppings[]" value="xmeat"/>Extra Meat</p>
<p><input type="checkbox" name="toppings[]" value="veg"/>Vegetarian</p>
if (isset($_POST["toppings"]))
{
    $toppings = $_POST["toppings"];
    for ($i = 0; $i < count($_POST["toppings"]); $i  )
    {
        printf("<p>Topping %s</p>", $_POST["toppings"][$i]);
        if ($toppings[$i] == "xchese")
        {
            $sando_total  = 1.50;
            printf("<p>Extra Cheese</p>");
        }
        else if ($toppings[$i] == "xmeat")
        {
            $sando_total  = 2.00;
            printf("<p>Extra Meat</p>");
        }
        else if ($toppings[$i] == "veg")
        {
            $sando_total  = 2.00;
            printf("<p>Vegetarian</p>");
        }
    }
}

Main issue happening in the for loop. It detects how many are being checked but not what the values are.

CodePudding user response:

First I'd use filter_input() to filter the input correctly and initialize $sando_total. And as already mentioned above use a foreach-loop:

<?php
    
$sando_total = 0;
$toppings    = filter_input(INPUT_POST, "toppings", FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);

if (!empty($toppings)) {
    foreach ($toppings as $item) {
        printf("<p>Topping %s</p>", $item);
        if ($item == "xchese") {
            $sando_total  = 1.50;
            printf("<p>Extra Cheese</p>");
        } else if ($item == "xmeat") {
            $sando_total  = 2.00;
            printf("<p>Extra Meat</p>");
        } else if ($item == "veg") {
            $sando_total  = 2.00;
            printf("<p>Vegetarian</p>");
        }
    }
}

CodePudding user response:

First of all, ditch the brackets on the checkboxes name tag. They are not needed.

If you change the method tag of the form element to GET you'll see that the checkboxes in the form are "posted" as :

page.php?toppings=xchese&toppings=xmeat&toppings=veg

In any case, iterating through the $_POST["toppings"] should be sufficient.

As we usually say in software development: It worked on my machine.

  • Related