codeislife codeislife - 4 months ago 7
HTML Question

php html checkboxes error

Can anyone tell my why part of my code is not displaying?

Here is my HTML form:

<form action="OrderOutput.php" method="Post">
<fieldset>
<legend>Select a Crust</legend>
<table>

<tr>
<td>
<input type="radio" name="choice" value="Thin">Thin
</td>
<td>
$1.00
</td>
</tr>

<tr>
<td>
<input type="radio" name="choice" value="Medium">Medium
</td>
<td>
$2.00
</td>
</tr>

<tr>
<td>
<input type="radio" name="choice" value="Thick">Thick
</td>
<td>
$3.00
</td>
</tr>
</table>
</fieldset>


<fieldset>
<legend>Select Toppings</legend>


<table>
<tr>
<td>
<input type="checkbox" name="check[]" value="Mushrooms">Mushrooms
</td>
<td>
$4.00
</td>
</tr>


<tr>
<td>
<input type="checkbox" name="check[]" value="Pepperoni">Pepperoni
</td>
<td>
$5.00
</td>
</tr>
</table>
</fieldset>
<input type="submit" name="checkout" value="Checkout">

</form>


When I send the values to my php page, it only displays this line:

$selected_crust = $_POST['choice'];

echo "Your selections: Crust: $selected_crust";


but not this:

foreach ($_POST['check'] as $selected_toppings) {
echo "Toppings: $selected_toppings ";
}


Is there something wrong with my html checkboxes that is causing the information to not display in php?

Answer

Your code is working correctly, you just need to catch if a user has submitted no checkboxes:

if ( isset($_POST['check']) && is_array($_POST['check']) )
{
    //If you want to just show toppings once, a simple implode will work:
    //echo "Toppings: ", implode(', ', $selected_toppings);

    foreach ($_POST['check'] as $selected_toppings) { 
       echo "Toppings: $selected_toppings ";
    }
}
else
{
    echo "Toppings: You didn't select any!";
}