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
Related
I am attempting to echo the name of a selected dropdown rather than its value. I understand that echoing a dropdown's value can be achieved by implementing something such as:
$no2 = $_POST['vehicleStyle'];
echo $no2;
where vehicleStyle is the name.
this is my code
<select name="vehicleStyle">
<option value="2">Volvo</option>
<option value="3">Saab</option>
<option value="4">Fiat</option>
<option value="5">Audi</option>
</select>
If I add
$no2 = $_POST['vehicleStyle'];
echo $no2;
to my code, I get either 2,3,4 or 5 (whichever is selected). How can I echo the dropdown name, either volvo, saab , fiat or audi?
NOTE: i use this code
$no2 = $_POST['vehicleStyle'];
echo $no2;
to show the price of the car which i set in value, but also i need to echo the text to show the name of the car, how i can do that?
if you don't need the values (2, 3, 4, 5), you can just use:
<select name="vehicleStyle">
<option>Volvo</option>
<option>Saab</option>
<option>Fiat</option>
<option>Audi</option>
</select>
but if you need both, you should do something like this:
$no2 = [
"2" => "Volvo",
"3" => "Saab",
"4" => "Fiat",
"5" => "Audi"
]$_POST['vehicleStyle'];
echo $no2;
be aware that if you change the dropdown in the future, you have to come back here and change also this array
Simple approach is give the value the same as the text in it!
<form method="post">
<select name="vehicleStyle">
<option value="Volvo">Volvo</option>
<option value="Saab">Saab</option>
<option value="Fiat">Fiat</option>
<option value="Audi">Audi</option>
</select>
<input type="submit" name="vehicleName">
</form>
if(isset($_POST['vehicleName'])){
echo $_POST['vehicleStyle'];
}
If you are also need both text(name) and value(id) as magnus eriksson Suggest you need to separate them like: id;name and explode it on the back end to get id as well as name.
<form method="post">
<select name="vehicleStyle">
<option value="2;Volvo">Volvo</option>
<option value="3;Saab">Saab</option>
<option value="4;Fiat">Fiat</option>
<option value="5;Audi">Audi</option>
</select>
<input type="submit" name="vehicleName">
</form>
if(isset($_POST['vehicleName'])){
list($id, $name) = explode(';', $_POST['vehicleStyle']);
echo $id.' => '.$name;
}
Thank you all,
i solved this by editing the code to:
<form method="post">
<select name="vehicleName">
<option value="2|volvo">Volvo</option>
<option value="3|saab">Saab</option>
<option value="4|fiat">Fiat</option>
<option value="5|audi">Audi</option>
</select>
<input type="submit" name="submit">
</form>
and
if(isset($_POST['submit']))
{
$no2=$_POST['vehicleName'];
$no2_explode=explode('|', $no2);
for text
<?php echo $no2_explode[1]; ?>
and for the price number
<?php echo $no2_explode[0]; ?>
I have a dropdown to display price ranges for searching.
HTML for dropdown:
<select name="price">
<option value="">All (-)</option>
<option value="">Rs.400 to Rs.1,000 (3)</option>
<option value="">Rs.1,000 to Rs.2,000 (6)</option>
<option value="">Rs.2,000 to Rs.4,000 (1)</option>
<option value="">Rs.4,000+ (1)</option>
</select>
Using this option values, now I need to separate first and second price from user selection.
Eg. If someone select Rs.400 to Rs.1,000 (3), then I need to get 400 and 1,000.
Can anybody tell me how can I do this in php. I tired it with php explode. but I could not figure this out correctly.
Hope somebody may help me out.
Thank you.
What about something like this:
HTML
<select name="price">
<option value="all">All (-)</option>
<option value="400|1000">Rs.400 to Rs.1,000 (3)</option>
<option value="1000|2000">Rs.1,000 to Rs.2,000 (6)</option>
<option value="2000|4000">Rs.2,000 to Rs.4,000 (1)</option>
<option value="Over">Rs.4,000+ (1)</option>
</select>
PHP
<?php
//Get the data from the form
$price = $_POST['price'];
$prices = explode("|", $price);
?>
For example, if the user selects "Rs.400 to Rs.1,000", the value of $prices will be:
$price[0] = "400";
$price[1] = "1000";
I hope that helps. If it doesn't, I suppose I wasn't clear on what you were asking.
Inspired by a previous answer. I'd suggest.
HTML
<select name="price">
<option value="|">All (-)</option>
<option value="400|1000">Rs.400 to Rs.1,000 (3)</option>
<option value="1000|2000">Rs.1,000 to Rs.2,000 (6)</option>
<option value="2000|4000">Rs.2,000 to Rs.4,000 (1)</option>
<option value="4000|">Rs.4,000+ (1)</option>
</select>
PHP
<?php
function get_numeric($val) {
if (is_numeric($val)) {
return $val + 0;
}
return false;
}
$price_selected = isset($_REQUEST['price']) && trim($_REQUEST['price'])!="" ? $_REQUEST['price'] : "|"; // sets a default value
list($lower, $upper) = array_map('get_numeric',explode('|', $price_selected, 2));
var_dump($lower); // false when there's no lower limit
var_dump($upper); // false when there's no upper limit
?>
Can anyone point me in the right direction with the below
I have this HTML in a FROM (simplified for this example):
=============== Start HTML ===================
<select name="Postage[]" id="Unique-ID">
<option value="1">Postage Option 1</option>
<option value="2">Postage Option 2</option>
<option value="3">Postage Option 3</option>
</select>
<input name="PostagePrice[]" id="Price-Unique-ID" value="" />
<select name="Postage[]" id="Unique-ID">
<option value="1">Postage Option 1</option>
<option value="2">Postage Option 2</option>
<option value="3">Postage Option 3</option>
</select>
<input name="PostagePrice[]" id="Price-Unique-ID" value="" />
<select name="Postage[]" id="Unique-ID">
<option value="1">Postage Option 1</option>
<option value="2">Postage Option 2</option>
<option value="3">Postage Option 3</option>
</select>
<input name="PostagePrice[]" id="Price-Unique-ID" value="" />
================== End HTML =====================
I am collecting this from the form and setting it to an array ($arrPostageOptions) with the below code:
=============== Start PHP ===================
if (isset($_POST['Postage'])) {
if (is_array($_POST['Postage'])) {
$n = count($_POST['Postage']);
for ($i = 0; $i < $n; ++$i) {
// check to only collect completed entries
if( !empty($_POST['Postage'][$i]) && !empty($_POST['PostagePrice'][$i]) ){
// assign to array
$arrPostageOptions[$i] = array( "Postage" => $_POST['Postage'][$i], "PostagePrice" => $_POST['PostagePrice'][$i], );
}
}
}
}
=============== End PHP ===================
This results in the following array
============ array result ===============
Array(
[0] => Array
(
[Postage] => 1
[PostagePrice] => 12
)
[1] => Array
(
[Postage] => 2
[PostagePrice] => 24
)
[2] => Array
(
[Postage] => 3
[PostagePrice] => 48
)
)
============ end array result ===============
The answer (I think) I want is for each array is :
1 & 12
2 & 24
3 & 48
(that the array numbers match the postage numbers is just coincidence, I only want ‘Postage’ and ‘PostagePrice’)
I am trying the following:
=========== start of what I am trying ==========
foreach ($arrPostageOptions as $id) {
while ($id) {
$Postage = $id["Postage"];
$PostagePrice = $id["PostagePrice"];
// echo $Postage.' '.$PostagePrice.'<br>';
unset($id);
if (!$listing_obj->addPostageOptions($ListingID, $PostageOptionID, $PostagePrice, $db)) {
$err_text .= 'An error occurred adding Postage Option'.$PostageOptionID;
}
}
}
====== end of what I am trying ==============
Unfortunately this is not working as I expect (but is the closest I have gotten) . I have also tried multiple foreach loops, but again I don’t get what im after
(unsettling the $id is stopping the loop from continuing for ever, but is also giving me PHP notices of Undefined variable $id)
I’m sure I know how to do this, but seem to have forgotten and have possible over complicated it as these arrays are still confusing the s**t out of me.
Any advice would be greatly welcomed!
Why not simply:
foreach ($arrPostageOptions as $postageOption) {
$postage = $postageOption["Postage"];
$postagePrice = $postageOption["PostagePrice"];
echo $postage.' '.$postagePrice.'<br>';
...
}
Sorry for renaming, but $id was too confusing for me.
I'm not entirely sure I understood what you want to do but it would seem to me that you want to iterate the array like this, but I'm not sure.
foreach ($arrPostageOptions as $id=>$array) {
foreach($array as $key=>$val){
// do your stuff here using where you can also reference $id
}
}
there are a couple of things I would like to say is that the isset function is a bit pointless here and it is best used along with a submit button, not for text fields and other inputs.
Also, you are declaring your array inside the loop so accessing it anywhere outside will give an undefined error.
I just used your form and updated the php script slightly to give the output you desire. Please have a look.
Your form
<form action="yourscript.php" method="POST">
<select name="Postage[]" id="Unique-ID">
<option value="1">Postage Option 1</option>
<option value="2">Postage Option 2</option>
<option value="3">Postage Option 3</option>
</select>
<input name="PostagePrice[]" id="Price-Unique-ID" value="" />
<select name="Postage[]" id="Unique-ID">
<option value="1">Postage Option 1</option>
<option value="2">Postage Option 2</option>
<option value="3">Postage Option 3</option>
</select>
<input name="PostagePrice[]" id="Price-Unique-ID" value="" />
<select name="Postage[]" id="Unique-ID">
<option value="1">Postage Option 1</option>
<option value="2">Postage Option 2</option>
<option value="3">Postage Option 3</option>
</select>
<input name="PostagePrice[]" id="Price-Unique-ID" value="" />
<input type="submit" value="submit" name="submit"/>
</form>
I added a submit button and a the method and action in the header just to make it a bit more clear.
And here is the script I used, pretty similar to yours
<?php
$arrPostageOptions = array();
if(isset($_POST['submit']))
{
$postage = $_POST['Postage'];
$postagePrice = $_POST['PostagePrice'];
$array_size = count($postage);
for($i = 0; $i < $array_size; $i++)
{
if(!empty($postage[$i]) && !empty($postagePrice[$i]))
{
$arrPostageOptions[$i] = array("Postage"=>$postage[$i],
"PostagePrice"=>$postagePrice[$i]);
}
}
print_r($arrPostageOptions);
}
?>
I check if the submit button is set/clicked and enter the loop. I define the array variable outside so it can be used anywhere in the program.
If you see the print_r result, you will see the array in the format you desire.
I hope I answered a couple of your questions.
At the same time, its better to always put your POST data into variables before using them so you can check them and control them better than directly using $_POST['name']. This will be of more use when you work with databases and other related things.
Hope this helps.
Thanks,
Shawn.
The while within the foreach is redundant. foreach will only continue as long as there is a new entry to become $id anyhow.
The loop should be fine if you remove the while. If you want to test whether the data is valid, test on the array keys themselves like by putting this in the loop
if(!$id["Postage"] || !$id["PostagePrice"]){
continue;
}
<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
I'm using search with combo box
Here is my combo box source code
<select name="salary" class="styled">
<option selected="selected" value=''>Any</option>
<option value="10000">10,000</option>
<option value="20000">20,000</option>
<option value="30000">30,000</option>
<option value="40000">40,000</option>
<option value="50000">50,000</option>
<option value="60000">60,000</option>
<option value="70000">70,000</option>
<option value="80000">80,000</option>
<option value="90000">90,000</option>
<option value="100000">100,000</option>
<option value="110000">110,000</option>
<option value="120000">120,000</option>
<option value="130000">130,000</option>
<option value="140000">140,000</option>
<option value="150000">150,000</option>
</select>
I would like to select value based on $salary=$_GET['salary']; if $salary empty I need to select first one as selected
To set a default value for an HTML select element, you need to give the appropriate <option> element the selected attribute. It would look like this:
<option value='50000' selected='selected'>50,000</option>
In your PHP code, you would add this by setting a string for each option, to either "selected='selected'" or blank, depending on whether that option is the one you want to have selected.
This is obviously far easier to put into a loop rather than writing the same code twenty times, so you would need to rewrite your output to create a loop for creating your options.
Hope that helps.
You can do something like this on creation...[not tested]
<?php
$options = array(
'10000' => '10,000',
...
'150000' => '150,000'
); //From MySQL
array_unshift($options, '' => 'Any');
$salary = isset($_GET['salary'])?$_GET['salary']:'';
?>
<select name="salary" class="styled">
<?php foreach ($options as $value=>$text){ ?>
<option <?php if($value == $salary){echo 'selected="selected"'; }?> value="<?php echo $value; ?>"><?php echo $text; ?></option>
<?php } ?>
</select>
If I understand your question correctly you want that if the person doesn't select any thing you want 10000 to be automatically selected for him. And I also assume that the options in the select list are static. So..
<?php
if($_GET['salary']=='')
$salary = 10000;
else
$salary = $_GET['salary'];
?>