Working on a course, and I'm struggling with making this happen. Basically, I want to have a bunch of checkboxes, that when checked are read by a php page and then displayed in an unordered html list. For instance, a pizza order form. Select what toppings are wanted, and then submit the form. It then returns the page saying what you ordered.
HTML
<html>
<head>
</head>
<body>
<h2>Pizza Order Form</h2>
<form method="post" action="processform.php">
<h3>Toppings:</h3>
<input type="checkbox" id="Pepperoni" name="Toppings" value="Pepperoni">
<label for="Pepperoni"> Pepperoni</label><br>
<input type="checkbox" id="Sausage" name="Toppings" value="Sausage">
<label for="Sausage"> Sausage</label><br>
<input type="checkbox" id="Bacon" name="Toppings" value="Bacon">
<label for="Bacon"> Bacon</label><br>
</form>
</body>
PHP Page
<?php
$Toppings = $_POST['Toppings'];
if(empty($Toppings)) {
echo "No Toppings Selected";
} else {
print_r($Toppings);
foreach($Toppings as $Topping) {
echo $Topping;
}
$ToppingList = implode(',', $Toppings);
}
?>
<html>
<head>
</head>
<body>
<h1>Pretend Pizza Purchase:</h1>
<h2> Order Details</h2>
<?php echo '<ul>';
foreach($ToppingList as $Topping)
{
echo '<li>';
echo $Topping;
echo'</li>';
}
echo '</ul>';
?>
</body>
</html>
CodePudding user response:
In order for php to consider your checkbox elements as an array, you have to add braces to their names like so
name=Toppings[]
CodePudding user response:
Problem
If the input is a checkbox, then there must be [] at the end of the attribute name. Otherwise, $_POST['Toppings'] is the last option selected.
For example, the user selects Pepperoni and Sausage, then $_POST['Toppings'] is Sausage.
Function []
When the form is submitted, $_POST['Toppings'] will be treated as an array, and you can manipulate the array.
Answer
HTML
<html>
<head>
</head>
<body>
<h2>Pizza Order Form</h2>
<form method="post" action="processform.php">
<h3>Toppings:</h3>
<input type="checkbox" id="Pepperoni" name="Toppings[]" value="Pepperoni">
<label for="Pepperoni"> Pepperoni</label><br>
<input type="checkbox" id="Sausage" name="Toppings[]" value="Sausage">
<label for="Sausage"> Sausage</label><br>
<input type="checkbox" id="Bacon" name="Toppings[]" value="Bacon">
<label for="Bacon"> Bacon</label><br>
</form>
</body>
PHP Page
<?php
$Toppings = $_POST['Toppings'];
if(empty($Toppings)) {
echo "No Toppings Selected";
} else {
print_r($Toppings);
foreach($Toppings as $Topping) {
echo $Topping;
}
$ToppingList = implode(',', $Toppings);
}
?>
<html>
<head>
</head>
<body>
<h1>Pretend Pizza Purchase:</h1>
<h2> Order Details</h2>
<?php echo '<ul>';
foreach($Toppings as $Topping)
{
echo '<li>';
echo $Topping;
echo'</li>';
}
echo '</ul>';
?>
</body>
</html>
