Using $_POST to get select option value from HTML

2019-01-01 15:18发布

I use select as below:

<select name="taskOption">
    <option>First</option>
    <option>Second</option>
    <option>Third</option>
</select>

How do I get the value from the select option and store it into a variable for future use, in PHP?

标签: php html arrays
8条回答
千与千寻千般痛.
2楼-- · 2019-01-01 15:52
<select name="taskOption">
      <option value="first">First</option>
      <option value="second">Second</option>
      <option value="third">Third</option>
</select>

$var = $_POST['taskOption'];
查看更多
只靠听说
3楼-- · 2019-01-01 15:58

Depends on if the form that the select is contained in has the method set to "get" or "post".

If <form method="get"> then the value of the select will be located in the super global array $_GET['taskOption'].

If <form method="post"> then the value of the select will be located in the super global array $_POST['taskOption'].

To store it into a variable you would:

$option = $_POST['taskOption']

A good place for more information would be the PHP manual: http://php.net/manual/en/tutorial.forms.php

查看更多
回忆,回不去的记忆
4楼-- · 2019-01-01 16:01

You can access values in the $_POST array by their key. $_POST is an associative array, so to access taskOption you would use $_POST['taskOption'];.

Make sure to check if it exists in the $_POST array before proceeding though.

<form method="post" action="process.php">
  <select name="taskOption">
    <option value="first">First</option>
    <option value="second">Second</option>
    <option value="third">Third</option>
  </select>
  <input type="submit" value="Submit the form"/>
</form>

process.php

<?php
   $option = isset($_POST['taskOption']) ? $_POST['taskOption'] : false;
   if ($option) {
      echo htmlentities($_POST['taskOption'], ENT_QUOTES, "UTF-8");
   } else {
     echo "task option is required";
     exit; 
   }
查看更多
春风洒进眼中
5楼-- · 2019-01-01 16:02
<select name="taskOption">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>

try this

<?php 
if(isset($_POST['button_name'])){
$var = $_POST['taskOption']
if($var == "1"){
echo"your data here";
}
}?>
查看更多
笑指拈花
6楼-- · 2019-01-01 16:04

Use this way:

$selectOption = $_POST['taskOption'];

But it is always better to give values to your <option> tags.

<select name="taskOption">
  <option value="1">First</option>
  <option value="2">Second</option>
  <option value="3">Third</option>
</select>
查看更多
墨雨无痕
7楼-- · 2019-01-01 16:05

Like this:

<?php
  $option = $_POST['taskOption'];
?>

The index of the $_POST array is always based on the value of the name attribute of any HTML input.

查看更多
登录 后发表回答