METANIT.COM

Handling select box (drop-down list) in a PHP form

This tutorial will show you how to add select boxes and multi-select boxes to a form, how to retrieve the input data from them, how to validate the data, and how to take different actions depending on the input.

Select box

Let’s look at a new input: a “select” box, also known as a “drop-down” or “pull-down” box. A select box contains one or more “options”. Each option has a “value”, just like other inputs, and also a string of text between the option tags. This means when a user selects “Male”, the “formGender” value when accessed by PHP will be “M”.

 p> What is your Gender? select name="formGender">  option value="">Select. option>  option value="M">Maleoption>  option value="F">Femaleoption>  select>  p> 

The selected value from this input was can be read with the standard $_POST array just like a text input and validated to make sure the user selected Male or Female.

 php  if(isset($_POST['formSubmit']) )   $varMovie = $_POST['formMovie'];  $varName = $_POST['formName'];  $varGender = $_POST['formGender'];  $errorMessage = "";   // - - - snip - - -  >  ?> 

It’s always a good idea to have a “blank” option as the first option in your select box. It forces the user to make a conscious selection from the box and avoids a situation where the user might skip over the box without meaning to. Of course, this requires validation.

( For a generic, easy to use form validation script, see PHP Form Validation Script )

Multi-select

Suppose you want to present a select box that allows the user to select multiple options.

Here is how to create such an input in HTML:

 label for='formCountries[]'>Select the countries that you have visited:label>br> select multiple="multiple" name="formCountries[]">  option value="US">United Statesoption>  option value="UK">United Kingdomoption>  option value="France">Franceoption>  option value="Mexico">Mexicooption>  option value="Russia">Russiaoption>  option value="Japan">Japanoption>  select> 

Please note the similarity to a checkbox group. First, set multiple=“multiple” as a property of the select box. Second, put [ ] at the end of the name. Finally, we don’t really need a “blank” option in this select box, because we can simply check to make sure the user selected something or not. To select multiple values, use the shift or ctrl buttons when clicking.

The PHP code to process this field is very similar to the checkbox code. $_POST[‘formCountries’] returns an array of the selected values.

 php  if(isset($_POST['formSubmit']))   $aCountries = $_POST['formCountries'];   if(!isset($aCountries))    echo("

You didn't select any countries!

\n");
> else $nCountries = count($aCountries); echo("

You selected $nCountries countries: "); for($i=0; $i $nCountries; $i++) echo($aCountries[$i] . " "); > echo("

"
);
> > ?>

As before, use “isset” is to make sure some values were selected.

Using switch

Now, let’s change the multi-select box back to a standard single select box. We want to now perform different actions based on what selection the user makes. You could write a bunch of “if” statements, but that could get messy. Let’s look at two ways: dynamic commands and the switch statement.

These two approaches have their pro’s and con’s. The switch method is basically a concise method of writing a bunch of “if” statements. Each case matches the variable passed the switch and performs all actions after that case up until a break statement. In this case, each case is redirecting to the corresponding page to the selected country. If the selected country is not found in one of the cases, the “default” case is assumed, and “Error!” is displayed.

The second method is just passing the selected value to the header function to redirect to the correct page.

The first method requires writing more code, but is more secure because it ensures the form only redirects to 6 pre-programmed cases, or else displays an error message and ends execution.

The second method is much more concise, but less secure because a malicious user could monkey around with the form and submit whatever value he wants. If using method 2, it’s a good idea to validate the selected country first, to make sure it won’t result in a redirect to a malicious page.

Download Sample Code

Download the PHP form select samples below:

Источник

Php form select option value post

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

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

Флажки или чекбоксы (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[]»

Источник

How to Get Selected Values from Select Option in PHP 8

This tutorial explains to you how to get single and multiple selected values from the select option or select dropdown list in PHP 8. We will also learn to add custom styling in select dropdown using HTML and CSS.

PHP Select Option PHP Select Option PHP Select Option

Please also check out our previous tutorial on Getting Multiple Checkboxes Values in PHP.

Create Select Box with Options

The HTML Select box is created with an option list, and it is used to create a dropdown list of possible options. A user clicks on the select dropdown and chooses one of the options based on the requirement. We can also use multiple tags with the select tag, which lets users select multiple values from the dropdown list.

form action="" method="post"> select name="Fruit"> option value="" disabled selected>Choose optionoption> option value="Apple">Appleoption> option value="Banana">Bananaoption> option value="Coconut">Coconutoption> option value="Blueberry">Blueberryoption> option value="Strawberry">Strawberryoption> select> input type="submit" name="submit" vlaue="Choose options"> form>

PHP 8 Get Single Selected Values of Select Box

We used $_POST to get the select option value if the value is selected it will be displayed to user else we will throw the error message.

 if(isset($_POST['submit'])) if(!empty($_POST['Fruit']))  $selected = $_POST['Fruit']; echo 'You have chosen: ' . $selected; > else  echo 'Please select the value.'; > > ?>

We added some CSS to add custom styling for select dropdown, You can check out the full code example below.

doctype html> html lang="en"> head> meta charset="utf-8"> meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> title>Select Dropdown Example in PHPtitle> style> .container < max-width: 350px; margin: 50px auto; text-align: center; >input[type="submit"] < margin-bottom: 20px; >.select-block < width: 300px; margin: 110px auto 30px; position: relative; >select < width: 100%; height: 50px; font-size: 100%; font-weight: bold; cursor: pointer; border-radius: 0; background-color: #1A33FF; border: none; border: 2px solid #1A33FF; border-radius: 4px; color: white; appearance: none; padding: 8px 38px 10px 18px; -webkit-appearance: none; -moz-appearance: none; transition: color 0.3s ease, background-color 0.3s ease, border-bottom-color 0.3s ease; >/* For IE .selectIcon < top: 7px; right: 15px; width: 30px; height: 36px; padding-left: 5px; pointer-events: none; position: absolute; transition: background-color 0.3s ease, border-color 0.3s ease; >.selectIcon svg.icon < transition: fill 0.3s ease; fill: white; >select:hover, select:focus < color: #000000; background-color: white; >select:hover~.selectIcon, select:focus~.selectIcon < background-color: white; >select:hover~.selectIcon svg.icon, select:focus~.selectIcon svg.icon < fill: #1A33FF; >style> head> body> div class="container mt-5"> form action="" method="post" class="mb-3"> div class="select-block"> select name="Fruit"> option value="" disabled selected>Choose optionoption> option value="Apple">Appleoption> option value="Banana">Bananaoption> option value="Coconut">Coconutoption> option value="Blueberry">Blueberryoption> option value="Strawberry">Strawberryoption> select> div class="selectIcon"> svg focusable="false" viewBox="0 0 104 128" width="25" height="35" class="icon"> path d="m2e1 95a9 9 0 0 1 -9 9 9 9 0 0 1 -9 -9 9 9 0 0 1 9 -9 9 9 0 0 1 9 9zm0-3e1a9 9 0 0 1 -9 9 9 9 0 0 1 -9 -9 9 9 0 0 1 9 -9 9 9 0 0 1 9 9zm0-3e1a9 9 0 0 1 -9 9 9 9 0 0 1 -9 -9 9 9 0 0 1 9 -9 9 9 0 0 1 9 9zm14 55h68v1e1h-68zm0-3e1h68v1e1h-68zm0-3e1h68v1e1h-68z">path> svg> div> div> input type="submit" name="submit" vlaue="Choose options"> form>  if(isset($_POST['submit'])) if(!empty($_POST['Fruit']))  $selected = $_POST['Fruit']; echo 'You have chosen: ' . $selected; > else  echo 'Please select the value.'; > > ?> div> body> html>

Get Multiple Selected Values of Select Dropdown in PHP

In this step we will learn can a user select multiple selected values from a select options box. Add the multiple tag with select tag also define array with name property.

select name="Fruits[]" multiple> option value="" disabled selected>Choose optionoption> option value="Apple">Appleoption> option value="Banana">Bananaoption> option value="Coconut">Coconutoption> option value="Blueberry">Blueberryoption> option value="Strawberry">Strawberryoption> select>

Make sure the Fruits array is not empty, run a foreach loop to iterate over every value of the select dropdown. Display the selected values else show the error message to the user.

 if(isset($_POST['submit'])) if(!empty($_POST['Fruits']))  foreach($_POST['Fruits'] as $selected) echo ' ' . $selected; > > else  echo 'Please select the value.'; > > ?>

Here is the final code of multi select box.

doctype html> html lang="en"> head> meta charset="utf-8"> meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> title>Multiple Select Dropdown in PHPtitle> style> .container < max-width: 350px; margin: 50px auto; text-align: center; >select < width: 100%; min-height: 150px; margin-bottom: 20px; >input[type="submit"] < margin-bottom: 20px; >style> head> body> div class="container mt-5"> form action="" method="post" class="mb-3"> select name="Fruits[]" multiple> option value="" disabled selected>Choose optionoption> option value="Apple">Appleoption> option value="Banana">Bananaoption> option value="Coconut">Coconutoption> option value="Blueberry">Blueberryoption> option value="Strawberry">Strawberryoption> select> input type="submit" name="submit" vlaue="Choose options"> form>  if(isset($_POST['submit'])) if(!empty($_POST['Fruits']))  foreach($_POST['Fruits'] as $selected) echo ' ' . $selected; > > else  echo 'Please select the value.'; > > ?> div> body> html>

Conclusion

We have completed PHP Select Option tutorial, and in this tutorial, we learned how to get single or multiple select box values using PHP 8 with some basic validation.

A Full-stack developer with a passion to solve real world problems through functional programming.

Источник

Читайте также:  Все блочные элементы html
Оцените статью