Looping through all _Post Variables and adding numerical values - php

I have a form that looks like this.
<form action="index.php" method="post">
<select name="dropdownOption">
<option value="First Choice +200">First Choice</option>
<option value="Second Choice +300">Second Choice</option>
</select>
<p><input type="checkbox" value="Rocket +100"> Rocket</p>
What I want to do is loop through every value sent in the _POST and then sum up every number after the '+' sign into a variable in the index.php file.
So for example if they chose the 'Second Choice' and ticked the 'Rocket' Checkbox it should add up to 400 (300+100).
In this example there is only two different options but in the final application there will be 20-30 different things that can vary which is why looping is necessary.
Also How can I loop through every element that is not hidden (so exclude hidden form elements).

foreach ($_POST as $post) {
$num = explode('+', $post);
if (is_numeric((int) end($num)) {
$sum += end($num);
}
}
If you need negative values you can just make your option look like this:
<option value="Second Choice +-300">Second Choice</option>

I'm considering you are storing the values sent using _POST in an array.
$total = 0;
foreach($selections as $sel){
$sep = $explode('+', $sel);
$value = (int)$sep[1];
$total += $value;
}

Why wouldn't you drop the text in the values, and keep only numeric data?
The values aren't visible anyway, but in your code, you can easily map the numeric values to the text.
In other words, you can have something like this:
$choices = array(
'1' => array('value' => '100', 'text' => 'First choice'),
'2' => array('value' => '150', 'text' => 'Second choice'),
'3' => array('value' => '250', 'text' => 'Third choice'),
);
And display the data like this (or any other way, but having the ids of choices in the value field):
<form action="index.php" method="post">
<select name="dropdownOption">
<?php foreach($choices as $id => $choice): ?>
<option value="<?php echo $id ?>"><?php echo $choice['text']; ?></option>
<?php endforeach; ?>
</select>
</form>
And then having the initial array, you can easily sum up all the data:
$sum = 0;
foreach($selected as $id){
$sum += $choices[$id]['value'];
}
And display data to the user too:
<?php foreach($selected as $id): ?>
<p>You chose <?php echo $choices[$id]['text']; ?></p>
<?php endforeach; ?>
This is a way better approach as it gives you a lot of flexibility.

Related

Use an array as select form

I am a beginner and I have written a piece of code to use an array values inside a select form, but I don't know how to get the chosen value.
What I have :
$list = '<select><option>' .implode('</option><option>',$apn).'</option></select>';
Now I would like to get the name of the chosen value but I don't know how.I tried to add
<select name="test">
to my select form and get it with
echo $_POST['test']
but it does not work.
Thank you !
<?php $myArray = array(1 => 'red', 2 => 'blue'); ?>
<select name="theName">
<?php
foreach ($myArray as $key => $value) { ?>
<option value="<?php $key ?>"><?php echo $value ?></option>
<?php } ?>
</select>
Basically, you are looping through the option value with a foreach statement and assigning the key as the value.
You then get the chosen value with name 'theName'... echo $_POST['theName'];

Fail to retrieve multiple values from select dropdown in PHP

The issue is i can only retrieve one value from the select dropdown even i have selected 2, have tried to look at similar question here,but none seems to work for me.
Any thoughts? Thanks
if (isset($_POST['submit'])){
$smsorcall = $_POST['smsorcall'];
foreach($smsorcall AS $index => $smsorcall ) {
echo "$smsorcall";}
}
<form action="newpatient.php" method="post">
<p>Reminder Preference: *</p>
<select name="smsorcall[]" style="width: 250px" class="form-control" multiple>
<option value="SMS">SMS</option>
<option value="Call">Call</option>
<option value="Email">Email</option>
</select>
<button type="submit" name="submit">Submit</button>
</form>
My code
<?php ob_start();
session_start();
include('connect-db.php');
if (isset($_POST['submit']))
{
$patientid = $_POST['patientid'];
$smsorcall = $_POST['smsorcall'];
foreach($smsorcall AS $index => $smsorcall ) {
echo "$smsorcall";}
$_SESSION['smsorcall'] = $smsorcall;
In another html page, i echo the $_SESSION['smsorcall'] to display the result
You are only saving the last value to the session - you should save the whole array from the POST, then when you want to get the values loop through the array from the session, e.g.:
if (isset($_POST['submit']))
{
// save the WHOLE ARRAY of selected options to the session
$_SESSION['smsorcall'] = $_POST['smsorcall'];
/* Any more code here... */
}
On your other page:
if (isset($_SESSION['smsorcall']))
{
// Get the array of all selected options from the session
$smsorcall = $_SESSION['smsorcall'];
// loop through the array to process each option one at a time
foreach($smsorcall AS $index => $option ) {
// Do whatever you want with each option here, e.g. to display it:
echo $option;
}
}

Get all values of option fields and push it into an array

Let's say I have a photo upload system where the user have to set a category for each album to get the basics for a nice and clean search functionality. But if an user is changing now a value like this:
<select>
<option value="">Choose a Category</option>
<option value="Holiday">Holiday</option>
</select>
to this:
<select>
<option value="">Choose a Category</option>
<option value="Holiday">Something Stupid</option>
</select>
is "something stupid" entered into the database.
That's why I have to do a server side check. But I don't know how to get all the correct values of the option fields to compare it with the posted value.
So my first considerations were the following:
PHP:
// Get all values of the option fields
// Push all the values into an array
if (in_array('foo', $array)) {
// foo is in the array
}
Thank you for helping.
Ok, so I think I guessed what you tried to tell.
You should not have the tags hardcoded in your list.php file, but instead have an array there. That way, you can use it both for generating the select field, but also for the verification. However, generally a database table with the categories would be preferable.
path/list.php
return array(
'1' => 'Name of Ctg 1',
'2' => 'Name of Ctg 2'
);
Here you generate the select
<select name="whatever">
<?php
$options = include('path/list.php');
foreach($options as $id => $name) {
echo '<option value="' . $id . '">' . $name . '</option>';
}
?>
</select>
And how to verify it then in the "target" page
$options = include('path/list.php');
if(!array_key_exists( $valueFromUser, $options ) ) {
// invalid option
}
When the data is posted from the page containing the select tag, it will be in the $_REQUEST array, if you run this php in catcher php page:
foreach ($_REQUEST AS $key => $value) echo "$key = $value <br>";
you will see the results from your list.php.

Add dynamic value to a hidden form field

I'm having a contact form field named, addons with select options
it's code is
<?php foreach ($addons as $options) { ?>
<option value="<?php echo $options->addon_name; ?>"><h5><?php echo $options->addon_name; ?></h5></option>
<?php } ?>
Every addon have it's unique price. It can be fetch through $options->addon_price; I added only addon name in contact form so i'm getting only it's name once user submits form. Likewise, I need to get that addon price too without creating new field and asking users to select price in dropdown.
Any ideas to do this ?
You can use the following trick:
<?php foreach ($addons as $options) { ?>
<option value="<?php echo $options->addon_name.','.$options->addon_price; ?>">
<h5><?php echo $options->addon_name; ?></h5>
</option>
<?php } ?>
Add the price with the name in value of dropdown and then after submitting the page you can get the string with name and price and then you can split it with the , by using the explode function like it:
$pieces = explode(",", $str);
And you can use the price and name by $name = $pieces[0] and $price = $pieces[1].
You Can use
<?php foreach ($addons as $options) { ?>
<option value="<?php echo $options->addon_price; ?>"><h5><?php echo $options->addon_name; ?></h5></option>
<?php } ?>
and u can fetch the price form the drop down
you can try this you will be able to get the price and it will show addon_name to the user.
<?php foreach ($addons as $options) { ?>
<option value="<?php echo $options->addon_price; ?>"><h5><?php echo $options->addon_name; ?></h5></option>
<?php } ?>
It sounds like you need a unique ID to identify the addons. If it's a static array that doesn't change, you can even use the array keys for that purpose, but I would add an addon_id field to the objects.
The addons array would be something like this:
$addons = array(
1 => $addon1,
2 => $addon2,
3 => $addon3,
... etc
);
Your select options can have the array keys as values:
<?php foreach ($addons as $key => $options) { ?>
<option value="<?php echo $key; ?>"><h5><?php echo $options->addon_name; ?></h5></option>
<?php } ?>
Then when you're processing the selected addon, use the key to access the appropriate addon, like so:
$selected_addon = $addons[$_POST['addon']];
, obviously substituting the correct form element name, and sanitizing the input first, this is just to give you an idea.

Set <select> tag selected value in PHP

What would be the best way to set tag selected value?
<select id="attr_field_10" name="config_eph_payment_type">
<option value="5">First</option>
<option value="1">Second</option>
<option value="2">Third</option>
<option value="3">Fourth</option>
<option value="4">Fifth</option>
<option value="7">Sixth</option>
</select>
The value comes from $config_eph_payment_type variable (5, 1, 2, 3, 4 or 7).
Something like this should work:
$options = array(
5 => "First",
1 => "Second",
...
7 => "Sixth"
);
echo "<select id=\"attr_field_10\" name=\"config_eph_payment_type\">";
foreach ($options as $k => $v) {
echo "<option value=\"$k\"";
if ($k == $config_eph_payment_type)
echo " selected";
echo ">$v</option>";
}
echo "</select>";
What we basically do is to store the options into an associative array. Then, we loop through it and keep checking if the value is equal to the variable $config_eph_payment_type.
<option value="5"<?php if ($config_eph_payment_type == 5) print ' selected="selected"'; ?>>First</option>
This is the easiest way to do it. You could also put the if at the beginning of the file and then define a variable, this would make the HTML code more readable
<?php
//at beginning
if ($config_eph_payment_type==5)
$fiveSelected = ' selected="selected"';
else
$fiveSelected = '';
?>
in your code
First

Categories