- Как узнать, установлен ли флажок в PHP
- Ответ 1
- Ответ 2
- Ответ 3
- Ответ 4
- Ответ 5
- Ответ 6
- Ответ 7
- Read if Checkbox Is Checked in PHP
- Use the isset() Function on $_POST Array to Read if Checkbox Is Checked
- Use the in_array() Function to Read if the Checkbox Is Checked for Checkboxes as an Array
- Use the isset() Function With Ternary Function to Read if the Checkbox Is Checked
- Consent to the use of Personal Data and Cookies
- See if a Checkbox is Checked in PHP
- Checking if a checkbox was checked
Как узнать, установлен ли флажок в PHP
Как прочитать, установлено ли значение в чекбоксе на PHP?
Ответ 1
Если ваша HTML-страница выглядит так:
,
п осле отправки формы вы можете проверить ее так:
isset($_POST[‘test’])
или
if ($_POST[‘test’] == ‘value1’) .
Ответ 2
Zend Framework использует хороший хак для чекбоксов, который вы также можете сделать сами. Каждый сгенерированный флажок ассоциируется с одноименным скрытым полем, расположенным непосредственно перед флажком и имеющим значение « 0 » . Тогда, если ваш флажок имеет значение « 1 » , вы всегда получите значение « 0 » или « 1 » в результирующем GET или POST.
Ответ 3
При использовании флажков в виде массива:
,
в ам следует использовать in_array() :
if(in_array(‘Orange’, $_POST[‘food’]))
echo ‘Orange был выбран!’;
>
Не забудьте сначала проверить, что массив установлен, например:
if(isset($_POST[‘food’]) && in_array(.
Ответ 4
Пусть ваш html для вашего чекбокса будет похож на:
Затем, после отправки формы, вам нужно проверить его:
if (isset($_POST[‘check1’]))
// флажок установлен
> else
// альтернативный вариант
>
Предположим, что check1 должно быть именем вашего флажка. А если метод отправки вашей формы — GET, то вам нужно проверить переменные $_GET, например так:
if (isset($_GET[‘check1’]))
// флажок установлен
>
Ответ 5
Я использую этот трюк уже несколько лет, и он отлично работает без каких-либо проблем для отмеченного состояния флажка при использовании с PHP и базой данных.
HTML код: (для страницы добавления):
?>>
Код PHP (используется для добавления/редактирования страниц):
$status = $_POST[‘status’];
if ($status == 1)
$status = 1;
> else
$status = 0;
>
Подсказка: значение всегда будет пустым, если только пользователь не проверил его. Итак, у нас уже есть PHP-код, чтобы перехватить его и сохранить значение равным 0. Затем просто используйте переменную $status для работы с базой данных.
Ответ 6
Но приведенные выше примеры работают только тогда, когда вы хотите использовать INSERT значение, и не полезны для UPDATE различных значений в разных столбцах, поэтому вот мой маленький трюк:
// Установка всех значений в 0
$queryMU =’UPDATE ‘.$db->dbprefix().’settings SET menu_news = 0, menu_gallery = 0, menu_events = 0, menu_contact = 0’;
$stmtMU = $db->prepare($queryMU);
$stmtMU->execute();
if(!empty($_POST[‘check_menus’]))
foreach($_POST[‘check_menus’] as $checkU)
try
// обновление только выбранных значений
$queryMU =’UPDATE ‘.$db->dbprefix().’settings SET ‘.$checkU.’= 1’;
$stmtMU = $db->prepare($queryMU);
$stmtMU->execute();
> catch(PDOException $e)
$msg = ‘Error: ‘ . $e->getMessage();>
>
>
HTML:
Секрет в том, чтобы сначала обновить все VALUES (в данном случае в 0), а поскольку отправляются только проверенные значения, это означает, что все, что вы получите, должно быть установлено в 1, поэтому все, что вам необходимо, устанавливается во флажках в значение 1.
Пример для PHP, но он применим для всех языков.
Ответ 7
Мы будем очень благодарны
если под понравившемся материалом Вы нажмёте одну из кнопок социальных сетей и поделитесь с друзьями.
Read if Checkbox Is Checked in PHP
- Use the isset() Function on $_POST Array to Read if Checkbox Is Checked
- Use the in_array() Function to Read if the Checkbox Is Checked for Checkboxes as an Array
- Use the isset() Function With Ternary Function to Read if the Checkbox Is Checked
We will demonstrate how to check whether the checkbox is checked in PHP using the isset() function on $_POST array. We provide the value of the name attribute of the input tag of HTML as the array element in the $_POST array.
We will introduce another method to read the checkbox if it is checked in PHP using the in_array() function. We use checkboxes as an array in this method. It means that the all name field in HTML input tag must contain the same array.
We will introduce a short-hand method to check if the checkbox is checked using the ternary operator. The method is more straightforward and shorter and uses the isset() function.
Use the isset() Function on $_POST Array to Read if Checkbox Is Checked
We can use the isset() function to check whether the checkbox is checked in PHP. The isset() function takes the $_POST array as argument. The $_POST array contains the specific value of the name attribute present in HTML form.
For example, create a form in HTML with POST method and specify the action to index.php . Create two checkboxes with names test1 and test2 , respectively. Save the file with .php extension. Create a PHP file named index.php . Apply two if conditions to isset() function with $_POST array as argument. Use test1 and test2 as the array elements in the $_POST arrays, respectively. Print the message specifying the respective value has been checked.
The example below uses the POST method to send the data in the form. It is secure while sending sensitive information through the form. Click here to know more about the POST method. The user checks both the checkbox in the form. Thus, the script outputs the way it is shown below. If the user had checked only the Option 1 , the script would output as checked value1 . It goes similar to Option 2 too.
# html 5 form action="index.php" method="post" > input type="checkbox" name="test1" value="value1"> Option 1 input type="checkbox" name="test2" value="value2"> Option 2 input type="submit" value="Submit"> form>
#php 7.x php if(isset($_POST['test1'])) echo "checked value1"."
"; > if(isset($_POST['test2'])) echo "checked value2"; > ?>
checked value1 checked value2
Use the in_array() Function to Read if the Checkbox Is Checked for Checkboxes as an Array
We can use the in_array() function to check whether an element lies within an array in PHP. The in_array() function takes the value to be checked as the first argument. The second argument of the function is the array where the value is to be checked. Check the PHP manual to know more about the in_array function. For this method to work, all the name attribute values in HTML form must be an array.
For example, assign the value of name attribute in HTML form with test[] array. Note it applies to all the checkbox type . First, in the PHP file, check whether the data has been submitted using the isset() function as done in the first method. But, do not use the [] brackets after the test while checking the posted data. Then, use in_array() function to check whether the value1 is in the $_POST[‘test’] array. Display the message.
At first, the example below checks whether the data is submitted in the form. If the condition is true, then it checks if value1 lies in the $_POST[‘test’] array using the in_array() function. The user checks the first checkbox in the form.
#html 5 form action="index.php" method="post" > input type="checkbox" name="test[]" value="value1"> Option 1 input type="checkbox" name="test[]" value="value2"> Option 2 input type="submit" value="Submit">
#php 7.x php if(isset($_POST['test'])) if(in_array('value1', $_POST['test'])) echo "Option1 was checked!"; > > ?>
Use the isset() Function With Ternary Function to Read if the Checkbox Is Checked
We can use a short-hand method to check if the checkbox has been checked in PHP. This method uses a ternary operator along with the isset() function. Please check the MSDN Web Docs to know about the ternary operator.
For example, set a variable $check to store the value of the ternary operation. Use the isset() function to check whether test1 has been checked in the checkbox. Print $check variable to show the result. In the example below, checked is displayed if the condition is true, and the unchecked is displayed if the condition is false. The user checks the second checkbox in the form. Therefore, the condition fails.
#html 5 form action="index.php" method="post" > input type="checkbox" name="test1" value="value1"> Option 1 input type="checkbox" name="test2" value="value2"> Option 2 input type="submit" value="Submit"> form>
#php 7.x php $check = isset($_POST['test1']) ? "checked" : "unchecked"; echo $check; ?>
Subodh is a proactive software engineer, specialized in fintech industry and a writer who loves to express his software development learnings and set of skills through blogs and articles.
Consent to the use of Personal Data and Cookies
This website needs your consent to use cookies in order to customize ads and content.
If you give us your consent, data may be shared with Google.
See if a Checkbox is Checked in PHP
Short totorial on how to work with checkboxes in HTML and PHP.
Checkboxes can be used in HTML forms to control settings related to whatever is being posted back to the server. For example, if you are creating a new blog post from a HTML form, checkboxes can be used to control whether certain data should be hidden or shown to your visitors when viewing the blog post.
If a checkbox is checked, the value will be included in the post. Therefor, keeping a static value of 1 should be sufficient in most cases. The name attribute allows you to distinguish the box from other form elements, so the value is not really that important.
To check a checkbox you can use the checked attribute, or alternatively avoid including it to leave the checkbox unchecked.
In your HTML, a checkbox should look like these below (all valid examples).
input type="checkbox" name="mycheckbox" value="1" checked="checked"> input type="checkbox" name="mycheckbox" value="1" checked>
Styling and placement of form elements is not part of this tutorial.
Note. Extra care should be taken to make sure your HTML form elements are accessible.
Form labels should have a for attribute that correspond with the ID of the input element that they are associated with.
Checking if a checkbox was checked
If a checkbox is checked, the value will be included in the HTTP POST and made available in the $_POST superglobal array. So, to find out if a box was checked, we can use an if statement to see if mycheckbox is found in the $_POST array. You can either use empty, or isset. It does not really matter, as long as you understand behavioral differences.
if (empty($_POST['mycheckbox'])) echo "Checked!"; > else echo 'Not checked!'; >
The above looks rather messy if you have a lot of code, so you may want to shorten the if statement, and keep it down to one line. The below will set the $my_checkbox variable to 1 if your checkbox is checked, or an empty string if not checked.
$my_checkbox = (empty($_POST['mycheckbox'])) ? 1 : '';
Since we are not using the value from our checkbox, the $my_checkbox variable can safely be inserted directly into a database without validation.