- PHP: Get Value of Select Option and Radio Button
- PHP Select Option
- A quick introduction to the element
- Getting the selected value from a element
- Select with multiple options
- Summary
- Php html select selected value
- Отправляем значение select на сервер
- Php код для отправки значения select на сервер
- Код select для получения данных через php:
- Пример получения значения из select php
- Получаем несколько значений(multiple) из select php
- Php получение нескольких значений select
- Show selected option value from Array & MySQL DB using PHP
PHP: Get Value of Select Option and Radio Button
HTML select tag allows user to choose one or more options from the given drop down list. Below example contains PHP script to get a single or multiple selected values from given HTML select tag. We are covering following operations on select option field using PHP script.
To get value of a selected option from select tag:
?>
To get value of multiple select option from select tag, name attribute in HTML tag should be initialize with an array [ ]:
?>
PHP script for RADIO BUTTON FIELD:
HTML allows user to choose one option from the given choices. Below codes contains PHP script to get a selected value from given HTML .
To get selected value of a radio button:
In below example, we have created a form having select tag and some radio buttons, As user submits it, Value of selected options will be displayed.
Watch our live demo or download our codes to use it.
Our complete HTML and PHP codes are given below.
PHP file: form.php
Given below our complete HTML contact form.
PHP Multiple Select Options and Radio Buttons
Radio 1 Radio 2 Radio 3 Radio 4 PHP file: select_value.php
To display multiple values, we used foreach loop here.
You have selected :
"; // As output of $_POST['Color'] is an array we have to use Foreach Loop to display individual value foreach ($_POST['Color'] as $select) < echo "".$select."
"; > > else < echo "Please Select Atleast One Color.
";> > ?>
PHP file: radio_value.php
To display radio buttons value.
You have selected : ".$_POST['radio'].""; > else< echo "Please choose any radio button.";> > ?>
CSS File: style.css
@import "http://fonts.googleapis.com/css?family=Droid+Serif"; /* Above line is used for online google font */ div.container < width:960px; height:610px; margin:50px auto; font-family:'Droid Serif',serif >div.main < width:308px; float:left; border-radius:5px; border:2px solid #990; padding:0 50px 20px >span < color:red; font-weight:700; display:inline-block; margin-bottom:10px >b < color:green; font-weight:700 >h2 < background-color:#FEFFED; padding:25px; margin:0 -50px; text-align:center; border-radius:5px 5px 0 0 >hr < margin:0 -50px; border:0; border-bottom:1px solid #ccc; margin-bottom:25px >label < color:#464646; text-shadow:0 1px 0 #fff; font-size:14px; font-weight:700; font-size:17px >select < width:100%; font-family:cursive; font-size:16px; background:#f5f5f5; padding:10px; border:1px solid >input[type=radio] < margin-left:15px; margin-top:10px >input[type=submit] < padding:10px; text-align:center; font-size:18px; background:linear-gradient(#ffbc00 5%,#ffdd7f 100%); border:2px solid #e5a900; color:#fff; font-weight:700; cursor:pointer; width:100%; border-radius:5px >input[type=submit]:hover
Conclusion:
Using these values you can perform other operations like CRUD (Create, Read, Update & Delete) in database. Hope you like it, keep reading our other blogs.
PHP Select Option
Summary: in this tutorial, you will learn how to use the element to create a drop-down list and a list box and how to get the selected values from the element in PHP.
A quick introduction to the element
The is an HTML element that provides a list of options. The following shows how to define a element in HTML:
label for="color">
Background Color: label> select name="color" id="color"> option value="">--- Choose a color --- option> option value="red">Red option> option value="green">Green option> option value="blue">Blue option> select>Code language: HTML, XML (xml)
The element has two important attributes:
- id – the id associates the element with a element
- name – the name attribute associates with the value for a form submission.
The element nested inside the element defines an option in the menu. Each option has a value attribute. The value attribute stores data submitted to the server when it is selected.
If an option doesn’t have the value attribute, the value attribute defaults to the text inside the element.
To select an option when the page loads for the first time, you can add the selected attribute to the element.
The following example selects the Green option when the page first loads:
label for="color">
Background Color: label> select name="color" id="color"> option value="">--- Choose a color --- option> option value="red">Red option> option value="green" selected>Green option> option value="blue">Blue option> select>Code language: HTML, XML (xml)
Getting the selected value from a element
We’ll create a form that uses a element.
First, create the following folders and files:
├── css | └── style.css ├── inc | ├── footer.php | ├── get.php | ├── header.php | └── post.php └── index.php
Code language: JavaScript (javascript)
Second, place the following code in the header.php file:
html>
html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> link rel="stylesheet" href="css/style.css"> title>PHP select option title> head> body class="center"> main>Code language: HTML, XML (xml)
Third, place the following code in the footer.php file:
main
> body> html>Code language: HTML, XML (xml)
Fourth, add the following code to the get.php file to create a form that has one element with a submit button:
form action="" method="post">
div> label for="color">Background Color: label> select name="color" id="color"> option value="">--- Choose a color --- option> option value="red">Red option> option value="green" selected>Green option> option value="blue">Blue option> select> div> div> button type="submit">Select button> div> form>Code language: HTML, XML (xml)
The form uses the POST method to submit data to the webserver.
Finally, add the following code to the post.php file:
$color = filter_input(INPUT_POST, 'color', FILTER_SANITIZE_STRING); ?> if ($color) : ?> p>You selected span style="color:"> echo $color ?> span>
p> p>a href="index.php">Back to the form a> p> else : ?> p>You did not select any color p> endif ?>Code language: HTML, XML (xml)
To get the selected value of the element, you use the $_POST superglobal variable if the form method is POST and $_GET if the form method is GET .
Alternatively, you can use the filter_input() function to sanitize the selected value.
If you select the first option of the element, the selected value will be empty. Otherwise, the selected value is red, green, or blue.
Select with multiple options
To enable multiple selections, you add the multiple attribute to the element:
select name="colors[]" id="colors" multiple>
. select>Code language: HTML, XML (xml)
When you select multiple options of a element and submit the form, the name will contain multiple values rather than a single value. To get multiple selected values, you add the square brackets ( []) after the name of element.
Let’s take a look at an example of using a element with multiple selections.
First, create the following folders and files:
. ├── css | └── style.css ├── inc | ├── footer.php | ├── get.php | ├── header.php | └── post.php └── index.php
Code language: JavaScript (javascript)
Second, place the following code into 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 Listbox title> link rel="stylesheet" href="css/style.css"> head> body class="center"> main>Code language: HTML, XML (xml)
Third, add the following code to the footer.php file:
main
> body> html>Code language: HTML, XML (xml)
Fourth, include the header.php and footer.php files in the index.php :
require __DIR__ . '/inc/header.php'; $request_method = strtoupper($_SERVER['REQUEST_METHOD']); if ($request_method === 'GET') < require __DIR__ . '/inc/get.php'; > elseif ($request_method === 'POST') < require __DIR__ . '/inc/post.php'; > require __DIR__ . '/inc/footer.php';
Code language: HTML, XML (xml)
If the HTTP request is GET, the index.php file will show a form from the get.php file. When the form is submitted, the post.php file will handle the form submission.
Fifth, create a form that contains a element with the multiple attribute in the get.php file. The name of the element has an opening and closing square bracket [] so that PHP can create an array that holds the select values.
form action="" method="post">
div> label for="colors">Background Color: label> select name="colors[]" id="colors" multiple> option value="red">Red option> option value="green">Green option> option value="blue">Blue option> option value="purple">Purple option> option value="magenta">Magenta option> option value="cyan">Cyan option> select> div> div> button type="submit">Submit button> div> form>Code language: HTML, XML (xml)
Finally, handle the form submission in the post.php file:
$selected_colors = filter_input( INPUT_POST, 'colors', FILTER_SANITIZE_STRING, FILTER_REQUIRE_ARRAY ); ?> if ($selected_colors) : ?> p>You selected the following colors: p>
ul> foreach ($selected_colors as $color) : ?> li style="color:"> echo $color ?> li> endforeach ?> ul> p> p> else : ?> p>You did not select any color. p> endif ?> a href="index.php">Back to the form a>Code language: HTML, XML (xml)
The post.php file uses the filter_input() function to get the selected colors as an array. If you select one or more colors, the post.php file will display them.
Summary
- Use the element to create a dropdown list.
- Use the multiple attribute to create a list that allows multiple selections.
- Use $_POST to get the selected value of the select element if the form method is POST (or $_GET if the form method is GET ).
- Add square brackets( [] ) after the name of the element to get multiple selected values.
Php html select selected value
Для того, чтобы получить значение из select в php вам потребуется:
Начнем с Html каркаса для получение из селект php:
Туда добавляем способ отправки — в нашем примере post
Если стоит задача, чтобы пользователь обязательно выбрал какой-то из пунктов select, то добавляем required
+ Обязательный атрибут атрибут name с произвольным значением «select_php»:
В option добавляем value со значениями(Один,Два,Три)
Отправляем значение select на сервер
Для того чтобы отправить»значение select на сервер» вам понадобится тип submit, это может быть input, либо button
Php код для отправки значения select на сервер
Php довольно простой. нам нужно проверить(условие if) массив post на наличие в нем имени php_select и получить его значение
Далее в этой же строке выводим. любой текст. echo
Соберем код получения значения из select php:
Код select для получения данных через php:
Код получения значения из select php соберем здесь:
if($_POST[php_select]) echo ‘Вы выбрали в select строку с номером : ‘ . $_POST[php_select].’ ‘;
Пример получения значения из select php
Выше я собрал весь код получения значения из select в php и далее выведем данный код прямо здесь::
Вам остается протестировать как работает пример кода select для получения значения через php:
Нажимаем по кнопке Выбрать php select и выбираем одно из значение селекта.
Потом нажимаем кнопку «Отправить php select«
Если что-то непонятно, вы всегда можете скачать готовый пример со страницы со всеми скриптами.
Получаем несколько значений(multiple) из select php
Возьмем теорию из выше описанных пунктов и + немного изменим код.
В теге form изменим атрибут «name»(+ изменим значение) добавим ему квадратные скобки, что будет означать получение массива или нескольких значений из select php
Чтобы при загрузке страницы сразу выбралось несколько значение . в пару строк добавлю «selected»
При использовании «multiple» select php будет отправлять массив, выводим с помощью print_r. Для вывода в строку используем «true»
Php получение нескольких значений select
if($_POST[php_select_arr]) $res_2 = ‘При «multiple» вы получите массив : ‘ . print_r($_POST[php_select_arr] , true).’ ‘;
?>
?
Show selected option value from Array & MySQL DB using PHP
In this tutorial, you will learn how to create an array of categories, display the values inside HTML select box and have selected options pre-defined with PHP and also I will show you how to get the selected options from a database using the ID of the record.
body < font-size: 2em; >.container < display: grid; grid-template-rows: repeat(2, 1fr); grid-template-columns: repeat(2, 1fr); grid-gap: 6rem; padding: 5rem; border: 1px solid #ccc; justify-content: space-evenly; >select Selected From Array Selected From DB Record "; foreach($options as $option)< if($selected == $option) < echo ""; > else < echo ""; > > echo ""; ?> if(isset($_GET['category'])) < $categoryName = $_GET['category']; $sql = "SELECT * FROM categories WHERE if($result = mysqli_query($link, $sql)) < if(mysqli_num_rows($result) >0) < while($row = mysqli_fetch_array($result))< $dbselected = $row['category']; >// Function frees the memory associated with the result mysqli_free_result($result); > else < echo "Something went wrong. "; >> else < echo "ERROR: Could not execute $sql." . mysql_error($link); >> $options = array('Comedy', 'Adventure', 'Drama', 'Crime', 'Adult', 'Horror'); echo ""; ?>
Thank you for reading this article. Please consider subscribing to my YouTube Channel.