Select all checkbox php code

PHP Checkbox

Summary: in this tutorial, you will learn how to use PHP to process a form with one or more checkboxes.

A quick introduction to the checkbox element

A checkbox allows you to select a single value for submission in a form. To create a checkbox, you use the input element with the type checkbox as follows:

input type="checkbox" name="checkbox_name" value="checkox_value">Code language: HTML, XML (xml)

A checkbox has two states: checked and unchecked.

If you check the checkbox and submit the form using the POST method, the $_POST associative array will contain an element whose key is checkbox_name and value is checkbox_value .

echo $_POST['checkbox_name']; // 'checkbox_value'Code language: PHP (php)

However, if you uncheck the checkbox and submit the form, the $_POST won’t have any element with key checkbox_name . It means that the following expression returns false :

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

To check if a checkbox is checked, you can also use the filter_has_var() function like this:

if(filter_has_var(INPUT_POST,'checkbox_name')) < // . >Code language: JavaScript (javascript)

The filter_has_var() function returns true if the checkbox_name exists in the INPUT_POST .

A checkbox has no label. Therefore, you should always use a checkbox with a element like this:

input type="checkbox" name="agree" id="agree"> label for="agree">I agree label>Code language: HTML, XML (xml)

In this example, the value of the for attribute of the element is the same as the value of the id attribute of the checkbox. When you associate a label with a checkbox, you can click the label to check or uncheck the checkbox.

Another way to associate a checkbox with a label is to place the checkbox inside the label like this:

label> input type="checkbox" name="agree"> I agree label>Code language: HTML, XML (xml)

In this case, you don’t need to specify the id for the checkbox and the for attribute for the label.

A simple PHP checkbox example

We’ll create a simple form with one checkbox and a submit button.

First, create the following directory and file structure:

. ├── css │ └── style.css ├── inc │ ├── .htaccess │ ├── get.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
header.php inc Contain the header code
footer.php inc Contain the footer code
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
.htaccess inc Prevent direct access to the files in the inc directory
style.css css Contain the CSS code

index.php

Second, add the following code to the index.php file:

 require __DIR__ . '/inc/header.php'; $errors = []; $request_method = $_SERVER['REQUEST_METHOD']; if ($request_method === 'GET') < require __DIR__ . '/inc/get.php'; > elseif ($request_method === 'POST') < require __DIR__ . '/inc/post.php'; > if ($errors) < require __DIR__ . '/inc/get.php'; > require __DIR__ . '/inc/footer.php';Code language: PHP (php)

The index.php loads the form from the get.php file if the HTTP request method is GET. And it loads the post.php file if the form is submitted.

The $errors variable is used to store error messages.

header.php

Third, place the following code to the header.php file:

html> html lang="en"> head> meta charset="UTF-8" /> meta name="viewport" content="width=device-width, initial-scale=1.0" /> title>PHP Checkbox title> link rel="stylesheet" href="css/style.css"> head> body class="center"> main>Code language: HTML, XML (xml)

Fourth, the footer.php file contains the enclosing tags corresponding to the opening tags from the header.php file:

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

get.php

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

"" method="post">  class hljs-title">error">php echo $errors['agree'] ?? '' ?> small> div> div> button type hljs-title">submit">Join Usbutton> div> form>Code language: PHP (php)

post.php

Sixth, add the following code to the post.php file to sanitize and validate the form data:

 // sanitize the value $agree = filter_input(INPUT_POST, 'agree', FILTER_SANITIZE_STRING); // check against the valid value if ($agree) < echo 'Thank you for joining us!'; > else < $errors['agree'] = 'To join us, you need to agree to the TOS.'; > Code language: PHP (php)

Summary

Источник

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.

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 [] .

Источник

Читайте также:  Адаптивное выпадающее меню html
Оцените статью