Check all checkbox html php

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.

Источник

Обработка чекбоксов в PHP

В этой статье мы расскажем о input type checkbox HTML , и том, как они обрабатываются в PHP .

Одиночный чекбокс

Создадим простую форму с одним чекбоксом:

 
Do you need wheelchair access?

В PHP скрипте ( checkbox-form.php ) мы можем получить выбранный вариант из массива $_POST . Если $_POST[‘formWheelchair’] имеет значение » Yes «, то флажок для варианта установлен. Если флажок не был установлен, $_POST[‘formWheelchair’] не будет задан.

Вот пример обработки формы в PHP :

Для $_POST[‘formSubmit’] было установлено значение “ Yes ”, так как это значение задано в атрибуте чекбокса value :

Вместо “ Yes ” вы можете установить значение » 1 » или » on «. Убедитесь, что код проверки в скрипте PHP также обновлен.

Группа че-боксов

Иногда нужно вывести в форме группу связанных PHP input type checkbox . Преимущество группы чекбоксов заключается в том, что пользователь может выбрать несколько вариантов. В отличие от радиокнопки, где из группы может быть выбран только один вариант.

Возьмем приведенный выше пример и на его основе предоставим пользователю список зданий:

 
Which buildings do you want access to?
Acorn Building
Brown Hall
Carnegie Complex
Drake Commons
Elliot House

Обратите внимание, что input type checkbox имеют одно и то же имя ( formDoor[] ). И что каждое имя оканчивается на [] . Используя одно имя, мы указываем на то, что чекбоксы связаны. С помощью [] мы указываем, что выбранные значения будут доступны для PHP скрипта в виде массива. То есть, $_POST[‘formDoor’] возвращает не одну строку, как в приведенном выше примере; вместо этого возвращается массив, состоящий из всех значений чекбоксов, которые были выбраны.

Например, если я выбрал все варианты, $_POST[‘formDoor’] будет представлять собой массив, состоящий из: . Ниже приводится пример, как вывести значение массива:

Если ни один из вариантов не выбран, $_POST[‘formDoor’] не будет задан, поэтому для проверки этого случая используйте » пустую » функцию. Если значение задано, то мы перебираем массив через цикл с помощью функции count() , которая возвращает размер массива и выводит здания, которые были выбраны.

Если флажок установлен для варианта » Acorn Building «, то массив будет содержать значение ‘ A ‘. Аналогично, если выбран » Carnegie Complex «, массив будет содержать C .

Проверка, выбран ли конкретный вариант

Часто требуется проверить, выбран ли какой-либо конкретный вариант из всех доступных элементов в группе HTML input type checkbox . Вот функция, которая осуществляет такую проверку:

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

Чтобы использовать ее, просто вызовите IsChecked ( имя_чекбокса, значение ). Например:

if(IsChecked('formDoor','A')) < //сделать что-то . >//или использовать в расчете . $price += IsChecked('formDoor','A') ? 10 : 0; $price += IsChecked('formDoor','B') ? 20 : 0;

Скачать пример кода

Скачать PHP код примера формы с PHP input type checkbox .

Источник

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

Источник

Читайте также:  Http tracker tfile ru announce php uk
Оцените статью