METANIT.COM

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.

See Also

Categories

  • Calculation Forms
  • HTML Forms
  • PHP Form Handling
  • Form Action
  • Contact Forms
  • Code Snippets
  • Best Practices
  • HTML5 Forms
  • Form Widgets
  • jQuery Form Handling
  • Email Forms
  • Form Mail
  • Web Forms
  • Checkboxes
  • File Upload
  • Google Forms

Источник

Обработка чекбоксов в 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 .

Источник

Input type checkbox name php

Формы могут содержать различные элементы — текстовые поля, флажки, переключатели и т.д., обработка которых имеет свои особенности.

Обработка флажков

Флажки или чекбоксы (html-элемент ) могут находиться в двух состояниях: отмеченном (checked) и неотмеченном. Например:

Checkbox в PHP

Если флажок находится в неотмеченном состоянии, например:

то при отправке формы значение данного флажка не передается на сервер.

Если флажок отмечен, то при отправке на сервер для поля remember будет передано значение on :

Если нас не устраивает значение on , то с помощью атрибута value мы можем установить нужное нам значение:

Иногда необходимо создать набор чекбоксов, где можно выбрать несколько значений. Например:

     "; > ?> 

Форма ввода данных

ASP.NET:

PHP:

Node.js:

В этом случае значение атрибута name должно иметь квадратные скобки. И тогда после отправки сервер будет получать массив отмеченных значений:

$technologies = $_POST["technologies"]; foreach($technologies as $item) echo "$item
";

В данном случае переменная $technologies будет представлять массив, который можно перебрать и выполнять все другие операции с массивами.

передача массива Checkbox input на сервер в PHP

Переключатели

Переключатели или радиокнопки позволяют сделать выбор между несколькими взаимоисключающими вариантами:

      ?> 

Форма ввода данных

ASP.NET
PHP
Node.js

radiobutton in PHP

На сервер передается значение атрибута value у выбранного переключателя. Получение переданного значения:

Список

Список представляет элемент select , который предоставляет выбор одного или нескольких элементов:

      ?> 

Форма ввода данных

Элемент содержит ряд вариантов выбора в виде элементов :

список select list в PHP

Получить выбранный элемент в коде PHP как и обычное одиночное значение:

Но элемент также позволяет сделать множественный выбор. И в этом случае обработка выбранных значений изменяется, так как сервер получает массив значений:

     "; > ?> 

Форма ввода данных

Такие списки имеют атрибут multiple=»multiple» . Для передачи массива также указываются в атрибуте name квадратные скобки: name=»courses[]»

Источник

Get checked Checkboxes value with PHP

Checkboxe­s are a versatile tool found in many we­bsites, allowing users to sele­ct their preferre­d choices among different options available­ with ease.

When you use it in your form and try to read all checked values as any other elements like – text box, text area, radio button, etc.

echo $_POST['lang']; // Checkbox element

you will get the last checked value.

You need to send the checkboxes value in the form of an Array when the form gets submitted then you can loop over $_POST values.

In this tutorial, I show how you can read submitted checked checkboxes values with PHP and also show how you can save it to the MySQL database.

Get checked Checkboxes value with PHP

Table of content

1. Read $_POST checked values

While creating multiple checkboxes add [] at the end of name attribute e.g. lang[] . Here, [] denotes an Array.

Select languages 
PHP
JavaScript
jQuery
Angular JS

When the form is submitted then loop over $_POST checkbox name using foreach .

 Select languages 
PHP
JavaScript
jQuery
Angular JS
'; > > > ?>

2. Demo

3. Create a Table to save checked checkboxes values

I am using languages table in the example.

CREATE TABLE `languages` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `language` varchar(80) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

4. Database Configuration

Create config.php file for database configuration.

Select languages
0) < $result = mysqli_fetch_assoc($fetchLang); $checked_arr = explode(",",$result['language']); >// Create checkboxes $languages_arr = array("PHP","JavaScript","jQuery","AngularJS"); foreach($languages_arr as $language) < $checked = ""; if(in_array($language,$checked_arr))< $checked = "checked"; >echo ' '.$language.'
'; > ?>

6. Conclusion

Next time when you use multiple checkboxes in your form then just initialize the name as an Array by putting [] in front and read it with loop when submitted.

Use implode() to convert checked values Array to string and store it in your MySQL database.

If you found this tutorial helpful then don’t forget to share.

Источник

Читайте также:  Python sockets close connection
Оцените статью