<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
<select name="test[]" multiple="multiple">
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
<option value="four">four</option>
<option value="five">five</option>
</select>
<input type="submit" value="Send" />
</form>
<?php
$test=$_POST['test'];
if ($test){
foreach ($test as $t){echo 'You selected ',$t,'<br />';}
}
if($t=='one')
$price1=12;
if($t=='two')
$price2=2;
$total = $price1 + $price2;
echo $total;
When one & two are both selected i'd like the result to be 14. What is the best way to make an addition to obtain 14 as a result ?
You should make one variable that will contain the result, instead of making price1, price2 and etc.
For example:
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
<select name="test[]" multiple="multiple">
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
<option value="four">four</option>
<option value="five">five</option>
</select>
<input type="submit" value="Send" />
</form>
<?php
$test = isset($_POST['test']) ? $_POST['test'] : null; // we also want to check if it's set else we'll get an notice
$total = 0;
if ($test) {
foreach ($test as $t) {
echo 'You selected ',$t,'<br />';
switch ($t) {
case "one" : $total += 2; break;
case "two" : $total += 12; break;
}
}
}
echo 'Total: ' .$total;
put that IF's into foreach loop
You must place the if $t = one , etc. inside the loop
Firstly, $test should be assigned using a ternary operator, that way we can make sure we don't cause PHP Warnings.
$test = isset($_POST['test']) ? $_POST['test'] : false;
if($test):
//good
endif;
Secondly, why even bother using string interpretation of an integer?
<option value="1">one</option> //note the values
<option value="2">two</option>
Lets make an array that has our answers.
$vals = array(
0 => 'Not an option!',
1 => 12,
2 => 2,
3 => 14,
4 => 26
);
Create a dummy variable we can use to concatenate the values posted.
$val = 0;
foreach($test as $t):
$val += $t;
endforeach;
Now $t will be the value of all the posted select items.
echo $vals[$val];
And that simple echo statement will supply you with your answer. This way you're not having to do multiple if/else statements, keeps it cleaner and more robust imo.
and here's a Codepad illustrating this
Related
I am trying to make a form submit.
Form is select a task, then show several rows with checkbox and select with values 1-10
If checkbox is selected is need to add values from select into database.
this is PHP code
if(isset($_POST) && $_SERVER['REQUEST_METHOD'] = 'POST'){
if(isset($_POST['submita'])){
foreach($_POST['nota'] as $key => $value)
if (isset($_POST['boxes'])){
foreach($_POST['boxes'] as $key => $value2){
if(isset($value2)){
$nota = htmlent($_POST['nota']);
$box = htmlent($_POST['boxes']);
$task = htmlent($_POST['task']);
$db->insert(array(
"task" => $task,
"nota" => $value,
"box" => $value2,
),
"erp_notes");
}
else
{
echo 'Select';
}
}
}
}
}
HTML
<input type="checkbox" name="boxes[]" value="<?=$row['id'];?>"></input>
<?=$row['name'];?>
<select name="nota[]" >
<option value="">Select</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
I try many time but nothing.
In the very first if you have = when you mean ==.
You haven't posted the entire HTML so I'll have to assume there is a submita element there that's being set. Your best bet is to do var_dump($_POST) to see what you are actually getting, and then build your code to match.
Your code is incorrect because it loops over every boxes for each nota, when what I suspect you want is to just check the checkbox that corresponds to that element.
You probably want something more like this:
if (isset($_POST['nota']))
{
for ($i = 0; $i < count($_POST['nota']); ++$i)
{
if (isset($_POST['boxes'][$i]))
$db->insert(array('task' => $task, 'nota' => $_POST['nota'][$i], 'box' => $_POST['boxes'][$i], 'erp_notes');
}
}
i was edited cod , but work like in comment from first answer
PHP
if(isset($_POST) && $_SERVER['REQUEST_METHOD'] == 'POST'){
if (isset($_POST['nota']))
{
for ($i = 0; $i < count($_POST['nota']); ++$i)
{
if (isset($_POST['boxes'][$i]))
$task = htmlent($_POST['task_id']);
$db->insert(array(
"nota" => $_POST['nota'][$i],
"date" => time(),
"box" => $_POST['boxes'][$i],
"task" => $task
),
"erp_note");
}
}
}
HTML
<form class="grid_12" action="" method="post" enctype="multipart/form-data">
<input type="checkbox" name="boxes[]" value="<?=$row['id'];?>"></input><?=$row['box_name'];?>
<select name="nota[]" multiple><option value="">select</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option></select>
<input name="task" type="text" value="<?=$row['task_id'];?>" style="display:none;">
</form>
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?
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>
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;
}
You can do it like this, too:
<?php
if(isset($_POST['select1'])){
$select1 = $_POST['select1'];
switch ($select1) {
case 'value1':
echo 'this is value1<br/>';
break;
case 'value2':
echo 'value2<br/>';
break;
default:
# code...
break;
}
}
?>
<form action="" method="post">
<select name="select1">
<option value="value1">Value 1</option>
<option value="value2">Value 2</option>
</select>
<input type="submit" name="submit" value="Go"/>
</form>
for php8+ versions, you can use match expression:
$select = $_POST['select1'] ?? '';
$result = match ($select) {
'value1' => 'this is value1',
'value2' => 'this is value2',
default => 'unknown value',
};
echo $result;
<select name="taskOption">
<option value="first">First</option>
<option value="second">Second</option>
<option value="third">Third</option>
</select>
$var = $_POST['taskOption'];
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
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.
<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";
}
}?>
-- html file --
<select name='city[]'>
<option name='Kabul' value="Kabul" > Kabul </option>
<option name='Herat' value='Herat' selected="selected"> Herat </option>
<option name='Mazar' value='Mazar'>Mazar </option>
</select>
-- php file --
$city = (isset($_POST['city']) ? $_POST['city']: null);
print("city is: ".$city[0]);
I'm trying to make this implode function work.
This is the form part, assume all the item has been selected.
<form method="post">
<select name="test1" multiple="multiple" id="test1">
<option value="1">item1</option>
<option value="2">item2</option>
<option value="3">item3</option>
<option value="4">item4</option>
<option value="5">item5</option>
</select>
</form>
The PHP part
<?php
$var1 = array();
$joinedString = array();
$var1 = $_POST['test1'];
$joinedString = implode(',', $var1);
?>
But The echoing part doesn't work, it gives me error, and only displaying only the first array value.
<?php
$echo $joinedString[0];
$echo $joinedString[1];
$echo $joinedString[2];
$echo $joinedString[3];
$echo $joinedString[4];
?>
Thank You guys, I'm quite new in programming. I always forgot that the code executed line by line, and always confused with variable and values, and yes, in real world I am also a clumsy & insignificant person.
<form method="post" action="sear.php">
<select name="test1[]" multiple="multiple" id="test1">
<option value="1">item1</option>
<option value="2">item2</option>
<option value="3">item3</option>
<option value="4">item4</option>
<option value="5">item5</option>
<input type="submit" name="submit" value="submit" />
</select>
</form>
<?php
$var1 = array();
$joinedString = array();
$var1 = $_POST['test1'];
$joinedString = implode(',', $var1);
echo $joinedString;
?>
After getting the post values it definitely works.... Try it...
Use
<select name="test1[]" multiple="multiple" id="test1">
In php file.
$var1 = isset($_POST['test1']) ? $_POST['test1']: 0 ;
print_r($var1); //gives array
foreach($var1 as $var) {
echo $var;
}
Change
<select name="test1" multiple="multiple" id="test1">
to
<select name="test1[]" multiple="multiple" id="test1">
And it's already an array
$var1 = $_POST['test1'];
$imploded = implode(",", $var1);
echo $imploded;
//FOR GETTING INDIVIDUAL ITEMS FROM array
echo $var1[0];
Implode is not getting any array. Its works on Array.
You are passing a string instead of an array. implode() turns an array into a string.
In your script, $_POST['test1'] will only contain the submitted value of the select box, not the entire set of values. Since $var1 contains only a string, implode() will error out.
Just look up this:
http://www.tizag.com/phpT/php-string-implode.php
And $ is used with variable.
You are trying to use implode your array using (,) but post array values does not contain values seperated by comma, therefore you will have to use foreach.
<?php
$var1 = array();
$joinedString = array();
$var1 = $_POST['test1'];
foreach($var1 as $values)
echo $values."<br/>";
?>
<form method="post">
<select name="test1[]" multiple="multiple" id="test1">
<option value="1">item1</option>
<option value="2">item2</option>
<option value="3">item3</option>
<option value="4">item4</option>
<option value="5">item5</option>
</select>
<input type="submit" >
</form>
I have created a populated dropdown list in HTML. When the two dropdowns have been selected, the form posts to 'calculate.php' where the php script echoes out the selected values from the dropdowns.
<form action="calculate.php" method='POST'>
<select name="Phones">
<option value="Lumia800">Nokia Lumia 800</option>
<option value="iPhone">Apple iPhone 4s</option>
<option value="GalaxyS2">Samsung Galaxy S2</option>
<option value="Bold9900">Blackberry Bold 9900</option>
<option value="SensationXE">HTC Sensation XE</option>
<option value="XperiaS">Sony Ericsson Xperia S</option>
</select>
<select name="Network">
<option value="Orange">Orange</option>
<option value="Vodafone">Vodafone</option>
<option value="O2">O2</option>
<option value="Three">Three</option>
</select>
<input type="submit" />
</form>
In this one example, 'calculate.php' echoes the selected dropdown values.
<?php
$pref=$_POST['Phones'];
$pref1=$_POST['Network'];
$Orange="5";
if ($pref1 == "Orange")
{
$total1 = $Orange;
}
$Lumia800="10";
if ($pref == "Lumia800")
{
$total = $Lumia800 + $Orange;
}
echo $total;
?>
This example output is '15'
The aim of this example is to eventually create a simple phone package system, with this set of code adding the price of the phone, the network costs, and other variables together for a final total of how much it would cost when the user submits it.
The problem I have is that I want to add each variable from the corresponding dropdown boxes ("Phones" and "Network" for example) against each other. Is my example going to be too over complicated for such a simple script? Is there a more refined method to get the results that I want?
Thanks,
JB.
You should define arrays for each select that contains all prices.
$phone_prices = array("Lumia800" => 10, "iPhone" => 42);
$network_prices = array("Orange" => 5, ...);
And then you coud simply do something like
$price = $phone_prices[$pref] + $network_prices[$pref1];
But this is not really safe, make sure $pref and $pref1 are existing indexes in their respective array.
It will work but might be complicated. I would suggest changing over to a switch statement instead.
$total = 0
switch ($pref) {
case "Orange":
$total += 5;
break;
case "O2":
$total += 8;
break;
}
Same switch structure would be for the $pref1 or network variable.
<form action="calculate.php" method='POST'>
<select name="Phones">
<option value="123">Nokia Lumia 800</option>
<option value="234">Apple iPhone 4s</option>
<option value="12">Samsung Galaxy S2</option>
<option value="32">Blackberry Bold 9900</option>
<option value="432">HTC Sensation XE</option>
<option value="12">Sony Ericsson Xperia S</option>
</select>
<select name="Network">
<option value="42">Orange</option>
<option value="34">Vodafone</option>
<option value="23">O2</option>
<option value="34">Three</option>
</select>
<input type="submit" />
</form>
and
<?php
echo $_POST['Network'] + $_POST['Phones'];
?>
might be a lot simpler in that case, but that of course depends on the exact situation where you need this.
G'day mate.
You could for one, create an array of mapping from Phones => Price and Network => Price
example:
<?php
$phones = array(
'Lumia800' => 10,
'iPhone' => 15,
'GalaxyS2' => 30,
// rest of the phones with price
);
$networks = array(
'Orange' => 10,
'Vodafone' => 15,
'Three' => 3,
'O2' => 8
);
then validate user input
if(!empty($phones[$pref])) && !empty($networks[$pref1])) {
echo $phones[$pref] + $networks[$pref1];
}
If your code isn't going to be more complicated then what i see now
I would just change:
...
<option value="iPhone">Apple iPhone 4s</option>
...
<option value="Orange">Orange</option>
...
to
...
<option value="5">Apple iPhone 4s</option>
...
<option value="10">Orange</option>
...
And then loop all the values at the end
$total = 0;
foreach ($_POST as $key => $val) {
$total += $val;
}
echo $total;
That way you can change the amount of dropdowns
This question already has answers here:
Using $_POST to get select option value from HTML
(8 answers)
Closed 6 years ago.
I am trying to get the option selected using PHP, but I ran out of ideas!
Below is the code I have tried until now:
<select>
<option value="1">Yes</options>
<option value="2">No</options>
<option value="3">Fine</options>
</select>
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">
So, what do I have to do?
Programmers are lazy...er....efficient....I'd do it like so:
<select><?php
$the_key = 1; // or whatever you want
foreach(array(
1 => 'Yes',
2 => 'No',
3 => 'Fine',
) as $key => $val){
?><option value="<?php echo $key; ?>"<?php
if($key==$the_key)echo ' selected="selected"';
?>><?php echo $val; ?></option><?php
}
?></select>
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">
<select>
<option value="1" <?php if ($myVar==1) echo 'selected="selected"';?>>Yes</options>
<option value="2" <?php if ($myVar==2) echo 'selected="selected"';?>>No</options>
<option value="3" <?php if ($myVar==3) echo 'selected="selected"';?>>Fine</options>
</select>
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">
This is a very simple and straightforward way, if I understand your question correctly.
you can use this..
<select name="select_name">
<option value="1"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='1')?' selected="selected"':'');?>>Yes</option>
<option value="2"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='2')?' selected="selected"':'');?>>No</option>
<option value="3"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='3')?' selected="selected"':'');?>>Fine</option>
</select>
First of all give a name to your select. Then do:
<select name="my_select">
<option value="1" <?= ($_POST['my_select'] == "1")? "selected":"";?>>Yes</options>
<option value="2" <?= ($_POST['my_select'] == "2")? "selected":"";?>>No</options>
<option value="3" <?= ($_POST['my_select'] == "3")? "selected":"";?>>Fine</options>
</select>
What that does is check if what was selected is the same for each and when its found echo "selected".
I suppose that you are using an array to create your select form input.
In that case, use an array:
<?php
$selected = array( $_REQUEST['yesnofine'] => 'selected="selected"' );
$fields = array(1 => 'Yes', 2 => 'No', 3 => 'Fine');
?>
<select name=‘yesnofine'>
<?php foreach ($fields as $k => $v): ?>
<option value="<?php echo $k;?>" <?php #print($selected[$k]);?>><?php echo $v;?></options>
<?php endforeach; ?>
</select>
If not, you may just unroll the above loop, and still use an array.
<option value="1" <?php #print($selected[$k]);?>>Yes</options>
<option value="2" <?php #print($selected[$k]);?>>No</options>
<option value="3" <?php #print($selected[$k]);?>>Fine</options>
Notes that I don't know:
how you are naming your input, so I made up a name for it.
which way you are handling your form input on server side, I used $_REQUEST,
You will have to adapt the code to match requirements of the framework you are using, if any.
Also, it is customary in many frameworks to use the alternative syntax in view dedicated scripts.
I use inline if's
($_POST['category'] == $data['id'] ? 'selected="selected"' : false)
I have 2 php files and i made this, and it works.
(this is an example) the first code is from the one file and the second code from two file.
<form action="two.php" method="post">
<input type="submit" class="button" value="submit" name="one"/>
<select name="numbers">
<option value="1"> 1 </option>
<option value="2"> 2 </option>
<option value="3"> 3 </option>
</select>
</form>
if(isset ($_POST['one']))
{
if($_POST['numbers']=='1')
{
$a='1' ;
}
else if($_POST['numbers']=='2')
{
$a='2' ;
{
else if ($_POST['numbers']=='3')
{
$a='3' ;
}
}
This answer is not relevant for particular recepient, but maybe useful for others.
I had similiar issue with 'selecting' right 'option' by value returned from database.
I solved it by adding additional tag with applied display:none.
<?php
$status = "NOT_ON_LIST";
$text = "<html>
<head>
</head>
<body>
<select id=\"statuses\">
<option value=\"status\" selected=\"selected\" style=\"display:none\">$status</option>
<option value=\"status\">OK</option>
<option value=\"status\">DOWN</option>
<option value=\"status\">UNKNOWN</option>
</select>
</body>
</html>";
print $text;
?>
This is the solution that I've came up with:
<form name = "form1" id = "form1" action = "#" method = "post">
<select name = "DropDownList1" id = "DropDownList1">
<?php
$arr = array('Yes', 'No', 'Fine' ); // create array so looping is easier
for( $i = 1; $i <= 3; $i++ ) // loop starts at first value and ends at last value
{
$selected = ''; // keep selected at nothing
if( isset( $_POST['go'] ) ) // check if form was submitted
{
if( $_POST['DropDownList1'] == $i ) // if the value of the dropdownlist is equal to the looped variable
{
$selected = 'selected = "selected"'; // if is equal, set selected = "selected"
}
}
// note: if value is not equal, selected stays defaulted to nothing as explained earlier
echo '<option value = "' . $i . '"' . $selected . '>' . $arr[$i] . '</option>'; // echo the option element to the page using the $selected variable
}
?>
</select> <!-- finish the form in html -->
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">
</form>
The code I have works as long as the values are integers in some numeric order ( ascending or descending ). What it does is starts the dropdownlist in html, and adds each option element in php code. It will not work if you have random values though, i.e: 1, 4, 2, 7, 6. Each value must be unique.