Php post from select option

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 post method from select option with jquery

For example, if you were to do it all in one PHP page. Another option is to ditch the numeric value altogether, and just use the country name as the value of the option. For example on page load because the default value of the variable = ‘bottomValue’ option three would be selected Solution 1: If you don’t want to use other technology, javascript for example, you have to check the value for each option like this: Solution 2: You need to do smth like this: Solution 3: first make Array of your values and then do this and then best thing abt this Method You dun need inline php code for eacchhh option:) Solution 4:

Php post method from select option with jquery

if(empty($_POST) === false) < $required_fields = array('s_group', 's_choice'); foreach($_POST as $key=>$value) < if(empty($value) && in_array($key, $required_fields) === true) < $error = 'All * fields are required'; break 1; >> if(empty($error) === true) < echo $_POST['s_group']; echo $_POST['s_choice']; echo $_POST['choice1']; echo $_POST['choice2']; >> echo $error; 
    

Number of Choice :

Insert your choice
1:
2:
Insert your choice
1:
2:
3:

I am a PHP newbie. After fill all blank, selected choice and hit submit button the value from s_group and s_choice are in $_POST but choice1 and choice2 aren’t come.

How can I get these value?

Rewrite the following code
Insert your choice

And dont duplicate your names of choices. Make your javascript in such a way that it will show/hide choice3, choice4 and choice 5 button on pagelist change.

Make only one instance of text input button Choice1, choice2 . and so on and hide/show individual text input via javascript on change of pagelist. You will get your variables in your post.

PHP $_POST, PHP $_POST PHP $_POST is a PHP super global variable which is used to collect form data after submitting an HTML form with method=»post». $_POST is also widely used to pass variables. The example below shows a form with an input field and a submit button.

PHP variable to select option

I have a php variable $valuable=’bottomValue’

and a select drop down inside a form which upon submit returns to the same page

Based upon the value of the $valuable how can I change the selected option to match.

For example on page load because the default value of the variable = ‘bottomValue’ option three would be selected

If you don’t want to use other technology, javascript for example, you have to check the value for each option like this:

You need to do smth like this:

first make Array of your values and then do this

$values = array ( 1 => 'topValue', 2 => 'middleValue', 3=> 'bottomValue', ); 
    

best thing abt this Method You dun need inline php code for eacchhh option:)

$valueable = 'bottomValue'; // array of the options you want to display in your select dropdown $options = array( 'topValue' => 'One', 'midValue' => 'Two', 'bottomValue' => 'Three' ); $html = '
'; $html .= ''; $html .= ''; $html .= '
'; echo $html;

Get Text From <option> Tag Using PHP

I want to get text inside the tags as well as its value.

I used $_POST[‘make’]; and I get the value 5 but I want to get both value and the text .

How can I do it using PHP?

In order to get both the label and the value using just PHP, you need to have both arguments as part of the value.

What about this? I think it’s the best solution because you have separated fields to each data. Only one hidden field which is updated at each change and avoids hardcoding mappings.

   function setTextField(ddl) 

set the value of text to the value of the option tag, be it through static HTML markup or even if it’s being generated by a server side script. You will only get the value attribute through POST

Another option however, on the server side, is to map the value («5»), to an associative array, i.e.

 "Text"); $value = $_POST['make']; //equals 5 $text = $valueTextMap[$value]; //equals "Text" ?> 

You’ll need to include that Text in the value to begin with (e.g.:and then parse, or.

You could use javascript on the page to submit the text as another parm in the POST action.

Html — PHP post method, Your script is requesting the URL welcome_get.php but you named your file welcome.php — you need to change one of them. Your code is currently searching for a file that doesn’t exist. If you want to post use method=»POST» not method=»get».. When you load the page your script looks for $_POST[‘name’] and …

Get option value AND text with PHP

Let’s say I have a HTML form: USA CDN And I select option 1 (USA) Then a php page Ok, duh, works fine and echo’s «1» How can I display «USA» as well? So in essence, I want to pass along the option’s TEXT also. How could I do this?

You would either need to change the option value on the HTML page to be the text you want displayed (poses a XSS security hazard) or on the page that’s displaying the text, you’d need an array where all the values match with the forum input.

Ex: $names[1] = «USA»; $names[2] = «CDN»; Then when you want to display it, you’d call $names[$selection] to output the text.

Another option you can consider is using javascript to update a hidden HTML element on the submitting page when the user makes their selection (using onUpdate). This information would be passed along with the submitted form data. Not the most secure or reliable of options, but an option nonetheless.

The client’s browser will not post back anything beyond the form element’s name and value — you would have to incorporate additional form fields and Javascript (or change the element’s value) to post «USA».

I suggest having a copy of the same data structure you used to print the form.

For example, if you were to do it all in one PHP page.

    You selected

Another option is to ditch the numeric value altogether, and just use the country name as the value of the option. However, for verification, you’ll still want the list of values. Check the differences in this example.

   Unknown country selection, wtf?> You selected

Html select option value in php Code Example, select query with multiple where clause in php. mysqli_fetch_all () expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\complete-blog-php\admin\includes\post_functions.php on line 31. retrieve data from database xampp. how to get create table query preview in …

Источник

Php post from select option

Для того, чтобы получить значение из 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).’‘;
?>

Источник

Читайте также:  What is request parameters in java
Оцените статью