Php forms with checkboxes

PHP Multiple Checkboxes

Summary: in this tutorial, you will learn how to handle a form with multiple checkboxes in PHP.

How to handle multiple checkboxes on a form

A form may contain multiple checkboxes with the same name. When you submit the form, you’ll receive multiple values on the server under one name.

To get all the values from the checked checkboxes, you need to add the square brackets ( [] ) after the name of the checkboxes.

When PHP sees the square brackets ( [] ) in the field name, it’ll create an associative array of values where the key is the checkbox’s name and the values are the selected values.

The following example shows a form that consists of three checkboxes with the same name ( colors[] ) with different values «red» , «green» , and «blue» .

form action="index.php" method="post"> input type="checkbox" name="colors[]" value="red" id="color_red" /> label for="color_red">Red label> input type="checkbox" name="colors[]" value="green" id="color_green" /> label for="color_red">Green label> input type="checkbox" name="colors[]" value="blue" id="color_blue" /> label for="color_red">Blue label> input type="submit" value="Submit"> form>Code language: HTML, XML (xml)

When you check three checkboxes and submit the form, the $_POST[‘colors’] will contain an array of three selected values:

array(3) < [0]=>string(3) "red" [1]=> string(5) "green" [2]=> string(4) "blue" > Code language: plaintext (plaintext)

If you don’t check any checkboxes and submit the form, the $_POST array won’t have the colors key. And you can use the isset() function to check if the $_POST[‘colors’] is set:

isset($_POST['colors'])Code language: PHP (php)

Alternatively, you can use the filter_has_var() function:

filter_has_var(INPUT_POST, 'colors')Code language: PHP (php)

PHP multiple checkboxes example

PHP multiple checkboxes example

First, create the following file and directory structure:

. ├── css │ └── style.css ├── img │ └── pizza.svg ├── inc │ ├── .htaccess │ ├── footer.php │ ├── functions.php │ ├── get.php │ ├── header.php │ └── post.php └── index.phpCode language: plaintext (plaintext)
File Directory Description
index.php . Contain the main logic that loads get.php or post.php depending on the HTTP request method
get.php inc Contain the code for showing a form with a checkbox when the HTTP request is GET.
post.php inc Contain the code for handling POST request
header.php inc Contain the code for the header
footer.php inc Contain the code for the footer
functions.php inc Contain the common functions
.htaccess inc Prevent direct access to the files in the inc directory
style.css css Contain the CSS code
pizza.svg img The pizza image that shows on the form

Second, add the following code to the header.php :

html> html lang="en"> head> meta charset="UTF-8" /> meta name="viewport" content="width=device-width, initial-scale=1.0" /> link rel="preconnect" href="https://fonts.gstatic.com"> link href="https://fonts.googleapis.com/css2?family=Nanum+Gothic+Coding:wght@400;700&display=swap" rel="stylesheet"> link rel="stylesheet" href="css/style.css"> title>PHP Multiple Checkboxes - Pizza Toppings title> head> body class="center"> main> p>img src="img/pizza.svg" height="72" width="72" title="Pizza Toppings"> p>Code language: HTML, XML (xml)

Note that the page uses the Nanum Gothic Coding font. The header.php links to the style.css file. At the beginning of the body, it shows the pizza.svg image.

Читайте также:  Python telegram bot aiogram кнопки

Third, add the following code to the footer.php :

 main> body> html>Code language: HTML, XML (xml)

The footer.php file contains the closing tags corresponding to the opening tags in the header.php file.

Fourth, define a function checked in the functions.php file:

 function checked($needle, $haystack) < if ($haystack) < return in_array($needle, $haystack) ? 'checked' : ''; > return ''; > Code language: PHP (php)

The checked() function returns the string ‘checked’ if the $need exists in the array $haystack or an empty string otherwise.

We’ll use this checked() function to refill the selected checkboxes on the form.

Fifth, add the following code to the index.php:

 session_start(); require 'inc/header.php'; require 'inc/functions.php'; $pizza_toppings = [ 'pepperoni' => 0.5, 'mushrooms' => 1, 'onions' => 1.5, 'sausage' => 2.5, 'bacon' => 1.0, ]; $request_method = $_SERVER['REQUEST_METHOD']; if ($request_method === 'GET') < require 'inc/get.php'; > elseif ($request_method === 'POST') < require 'inc/post.php'; > require 'inc/footer.php'; Code language: PHP (php)

The index.php calls the session_start() function to start (or resume) a session. It loads the code from the header.php, functions.php, and footer.php.

The $pizza_toppings array stores the pizza toppings and prices. In a real application, you may get it from a database or an API.

If the HTTP method is GET, the index.php loads the form from the get.php file. In case the HTTP method is POST, it loads the code from the post.php file.

Sixth, create a form in the get.php file:

"" method="post"> h1>Please select your pizza toppings: h1> ul>  foreach ($pizza_toppings as $topping => $price) : ?> li> div> input type="checkbox" name="pizza_toppings[]" value="" id="pizza_topping_" php echo checked($topping, $_SESSION['selected_toppings'] ?? []) ?> /> label for="pizza_topping_"> echo ucfirst($topping) ?> label> div> span> echo '$' . $price ?> span> li>  endforeach ?> ul> button type="submit">Order Now button> /form>Code language: JavaScript (javascript)

The get.php file uses the $pizza_toppings array to dynamically generate checkboxes. The checked() function checks the checkbox if the value exists in the $_SESSION[‘selected_toppings’] variable.

When the page loads for the first time, the $_SESSION[‘selected_toppings’] is always empty. Later, we’ll add the selected values to it in the post.php.

Finally, place the code to handle form submission in the post.php file:

 // sanitize the inputs $selected_toppings = filter_input( INPUT_POST, 'pizza_toppings', FILTER_SANITIZE_STRING, FILTER_REQUIRE_ARRAY ) ?? []; // select the topping names $toppings = array_keys($pizza_toppings); $_SESSION['selected_toppings'] = []; // for storing selected toppings $total = 0; // for storing total // check data against the original values if ($selected_toppings) < foreach ($selected_toppings as $topping) < if (in_array($topping, $toppings)) < $_SESSION['selected_toppings'][] = $topping; $total += $pizza_toppings[$topping]; > > > ?>  if ($_SESSION['selected_toppings']) : ?> h1>Order Summary h1> ul>  foreach ($_SESSION['selected_toppings'] as $topping) : ?> li> span> echo ucfirst($topping) ?> span> span> echo '$' . $pizza_toppings[$topping] ?> span> li>  endforeach ?> li class="total">span>Total span>span> echo '$' . $total ?> span> li> ul>  else : ?> p>You didn't select any pizza toppings. p>  endif ?> menu> a class="btn" href="" title="Back to the form">Change Toppings a> menu>Code language: HTML, XML (xml)

The post.php file sanitizes the form input using the filter_input() function:

// sanitize the inputs $selected_toppings = filter_input( INPUT_POST, 'pizza_toppings', FILTER_SANITIZE_STRING, FILTER_REQUIRE_ARRAY ) ?? [];Code language: PHP (php)

It checks selected pizza toppings against the original values in the $pizza_toppings array and adds the selected values to the $_SESSION[‘selected_toppings’] variable. Also, it calculates the total price based on the selected pizza toppings.

$toppings = array_keys($pizza_toppings); $_SESSION['selected_toppings'] = []; // for storing selected toppings $total = 0; // for storing total // check data against the original values if ($selected_toppings) < foreach ($selected_toppings as $topping) < if (in_array($topping, $toppings)) < $_SESSION['selected_toppings'][] = $topping; $total += $pizza_toppings[$topping]; > > >Code language: PHP (php)

The markup part shows the order summary if one or more pizza toppings are selected.

Summary

  • Add square brackets ( [] ) at the end of the checkbox name when a form has multiple checkboxes with the same name.
  • PHP creates an associative array to stored values of the selected checkboxes if checkboxes have the same name that ends with [] .

Источник

Handling checkbox in a PHP form processor

This tutorial will introduce HTML check boxes and how to deal with them in PHP.

Single check box

Let’s create a simple form with a single check box.

 form action="checkbox-form.php" method="post">  Do you need wheelchair access?  input type="checkbox" name="formWheelchair" value="Yes" />  input type="submit" name="formSubmit" value="Submit" />  form> 

In the PHP script (checkbox-form.php), we can get the submitted option from the $_POST array. If $_POST[‘formWheelchair’] is “Yes”, then the box was checked. If the check box was not checked, $_POST[‘formWheelchair’] won’t be set.

Here’s an example of PHP handling the form:

 php  if(isset($_POST['formWheelchair']) &&  $_POST['formWheelchair'] == 'Yes')   echo "Need wheelchair access."; > else   echo "Do not Need wheelchair access."; >  ?> 

The value of $_POST[‘formSubmit’] is set to ‘Yes’ since the value attribute in the input tag is ‘Yes’.

input type="checkbox" name="formWheelchair" value="Yes" /> 

You can set the value to be a ‘1’ or ‘on’ instead of ‘Yes’. Make sure the check in the PHP code is also updated accordingly.

Check box group

There are often situations where a group of related checkboxes are needed on a form. The advantage of check box group is that the user can select more than one options. (unlike a radio group where only one option could be selected from a group).

Let’s build on the above example and give the user a list of buildings that he is requesting door access to.

 form action="checkbox-form.php" method="post">  Which buildings do you want access to?br /> input type="checkbox" name="formDoor[]" value="A" />Acorn Buildingbr /> input type="checkbox" name="formDoor[]" value="B" />Brown Hallbr /> input type="checkbox" name="formDoor[]" value="C" />Carnegie Complexbr /> input type="checkbox" name="formDoor[]" value="D" />Drake Commonsbr /> input type="checkbox" name="formDoor[]" value="E" />Elliot House  input type="submit" name="formSubmit" value="Submit" />  form> 

Please note that the checkboxes have the exact same name ( formDoor[ ] ). Also notice that each name ends in [ ] . Using the same name indicates that these checkboxes are all related. Using [ ] indicates that the selected values will be accessed by PHP script as an array. That is, $_POST[‘formDoor’] won’t return a single string as in the example above; it will instead return an array consisting of all the values of the checkboxes that were checked.

For instance, if I checked all the boxes, $_POST[‘formDoor’] would be an array consisting of: . Here’s an example of how to retrieve the array of values and display them:

 php  $aDoor = $_POST['formDoor'];  if(empty($aDoor))    echo("You didn't select any buildings.");  >  else    $N = count($aDoor);   echo("You selected $N door(s): ");  for($i=0; $i  $N; $i++)    echo($aDoor[$i] . " ");  >  > ?> 

If no checkboxes are checked, $_POST[‘formDoor’] will not be set, so use the “empty” function to check for this case. If it’s not empty, then this example just loops through the array ( using the “count” function to determine the size of the array ) and prints out the building codes for the buildings that were checked.

If the check box against ‘Acorn Building’ is checked, then the array will contain value ‘A’. similarly, if ‘Carnegie Complex’ is selected, the array will contain C.

Check whether a particular option is checked

It is often required to check whether a particular option is checked out of all the available items in the checkbox group. Here is the function to do the check:

 function IsChecked($chkname,$value)    if(!empty($_POST[$chkname]))    foreach($_POST[$chkname] as $chkval)    if($chkval == $value)    return true;  >  >  >  return false;  > 

In order to use it, just call IsChecked(chkboxname,value). For example,

 if(IsChecked('formDoor','A'))  //do somthing .  > //or use in a calculation .  $price += IsChecked('formDoor','A') ? 10 : 0; $price += IsChecked('formDoor','B') ? 20 : 0; 

Download Sample Code

Download the PHP form checkbox sample code: php-form-checkbox.zip.

Источник

Оцените статью