METANIT.COM

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
Читайте также:  Java string tokens to array

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

В этой статье мы расскажем о 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 checkbox 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.

Источник

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