php associative array and switch - php

My associative array.
$money = array("Nickels" => $_POST["nickels"], "Dimes" => $_POST["dimes"], "Quarters" =>$_POST["quarters"]);
My html form set up to handle Quarters,
Dimes and Nickels are not shown in this case for brevity.
<label><b>Quarters:</b></label>
<select name="quarters" >
<option value=".25">25c</option>
<option value=".50">50c</option>
<option value=".75">75c</option>
<option value="1">$1.00</option>
</select>
A user can only select either Quarters only, Dimes only, or Nickels only.
If a user selects Quarters with the option value of .25, this value will be sent to
the php script.
So I was just wondering for calculations based on the fact that the user can select
Quarters only with one value, Dimes only with one value, and Nickels only with one
value, and not a combination of denominations,
how would one go about setting up different test cases, for example if the user selects
$money["Quarters"]; // With different values coming from the html form as .25, .50,.75, or 1, and only one of the selected values will make it through to the php script depending on what the user selected.
Can I do this:
switch($selection)
{
case “Quarters”:
echo “ You chose $money[‘Quarters’]; .<br />”;
break;
case “Nickels”:
echo “You chose $money[‘Nickels’]; .<br />”;
break;
case “Dimes”:
echo “You chose $money[‘Dimes’]; . <br />”;
break;
default: print “Please select a Denomination”;
}
Thank you for not flaming the newb, I am still learning, and sorry for the mix and match in terms of " and “.

Selected values in a form are submitted as $_POST['quarters'].
I understand, that you want to check, if the user has selected more than one of your <select>s (correct?)
So, I'd create a check like this:
$selected = 0;
if ($_POST['quarters'] != "DEFAULT_VALUE_OF_YOU_SELECT_QUARTERS")
{
$selected++;
}
if ($_POST['nickels'] != "DEFAULT_VALUE_OF_YOU_SELECT_NICKELS")
{
$selected++;
}
if ($_POST['dimes'] != "DEFAULT_VALUE_OF_YOU_SELECT_DIMES")
{
$selected++;
}
if ($selected > 1)
{
// The user has selected more than one
}

There's a few things to pay attention to here.
So, first of all, your $money array captures every value the user submits.
Next, the way you have your HTML <select> statement set up, there's no default value. The first option in $_POST["quarters"] is going to be .25 even if the user never touches that pulldown. To avoid this, you would want to add to the Quarters <select>:
<option value="0">-- Select Quarters --</option>
But still this doesn't allow you to use a switch/case statement. You're still going to be submitting a value for EVERY HTML <select> tag. Florian Peschka's solution is better, since it checks every pulldown, making sure they only used one, and perhaps displays a message if they don't.
Finally... I don't know what $selection refers to in your example. You're populating the $money array, so the $selection variable doesn't exist.
I can further help if you clarify your question.

Related

If option value is not available in the select form, show error

Sorry if the title is not clear enough, here is the explaination :
I got a MYSQL Database named "perso", with "perso_name in it". The perso_name are the same as the values in my select form. Here is the HTML code :
<form method="post">
<select name="selectperso" onchange="showUser(this.value)">
<option value="op1">Option1</option>
<option value="op2">Option2</option>
</select>
<input type="submit" name="validperso" value="Confirm">
</form>
Here is the PHP code :
<?php
$error = 0;
if (isset($_POST['validperso'])) {
if ($error !== 0) {
echo"<script>alert(\"Error\")</script>"; }
else {
echo "<script>alert(\"Working\")</script>";
}
}
?>
Now, what i want to do is kinda tricky.
Let's say i have "op3" in my database, but the user can't have it. The problem is that the user can modify the value "op1" to "op3" and then he will have the op3. I want to make a condition which says "if the user select one of the "op" value available in the select, then it's ok. Else, error++."
Thanks for the help !
Okay, I write more info about your problem.
Usually what you need is called whitelisting - you create a list of some things, that are allowed for user.
It can be simple array like:
$allowed_options = ['op1','op2','op3'];
if (!in_array($userInput, $allowed_options)) {
// input not allowed, do something
}
Or more complicated logic like a query to mysql:
select * from table where option = "USER_INPUT" and user_role = 'SOME_ROLE'
Anyway, only you as a developer know how to limit user's activity.
If, for example, you create your select from array of values:
foreach ($values as $v) {
echo '<option value="' . $v . '">VALUE</option>";
}
Then use same array $values to check if user input is allowed.
Same to mysql queries or other ways of getting required content.
To achieve your target better way you bind user with options in DB (i.e. Like username and Password) and then every time you validate user and options.
Another way you can put a hidden field with correct option and user mapped. And every time you can matched user selected option with hidden field value. This is not secure method.

select options to apply to different users

dropmenu is <select name="dropbox"> with 3 options - admin, activate, delete. The below snippet of code shows if the activate <option> is selected and submitted by the submit button then echo etc. I have a <select name="dropbox"> on every row for each user. My code only works if i change the last drop box.
if(isset($_POST['submit']))
{
if(isset($_POST['dropmenu']) && $_POST['dropmenu'] == 'activate')
{
echo 'is activated';
}
else{
echo 'fail';
}
}
Is there a way i can use foreach drop box with a value selected?
One of the possible ways is to connect the name of the select element with user id like
<select name="dropbox_[userId]">
In this case you simply know how to build an input name for checking it's value in $_POST table.
If you don't interate by users on submit code then you can use a regular expression to get an inforamtion abut user connected with element.

Replace PHP values in $_POST (for mailing)

This is driving me crazy and I couldn't find information that could help me figure this out.
I have a simple check-in form as follows:
<label for="adults" class="field-label"> Adults</label>
<label class="field select prepend-icon">
<select id="adults" name="adults" onChange="updatesum()">
<option value="0">...</option>
<option value="300">1</option>
<option value="600">2</option>
<option value="900">3</option>
</select>
</label>
Those option values are prices used to calculate the price per person and the text is actually the amount of adults checkin-in.
What I can't figure out is that when I submit the form the PHP posts the value of the field instead of the amount of adults checking in which are between 1 and 3 max.
$adults = strip_tags(trim($_POST["adults"]));
Can i replace that values before sending the email to something like this:
If the value = 300 then replace with 1
If the value = 600 then replace with 2
If the value = 900 then replace with 3
and then send the email with the number of adults and not the price.
Can anybody give me a hand?? thanks!!
You can check it live here westermansfrigga.se and press the button "boka nu", that's the form I'm making.
It's still in testing phase you can make test bokings and you should get the corresponding emails. For a clear understanding of what I mean with replacing the values. In the confirmation email adults = 300 instead of 1.
The behaviour of your form is the expected one. The value of the field is sent, not its text. So
<option value="ThisWillBeSent">This will NOT be sent</option>
I imagine that you use "value" for some operation on onChange (so if I were you, I would add that script to the question). The best solution would be to have a different attribute holding the number:
<option data-value="300" value="1">One Adult</option>
This way, the number of adults gets sent, and the client still has the amount to work upon. In the javascript you read the new attribute, e.g. in jQuery,
sum += $el.attr("data-value")
instead of
sum += $el.attr("value")
If you're using plain Javascript, then you would have something like
var combo = document.getElementById("adults");
var adultValue = combo.options[combo.selectedIndex].getAttribute("data-value");
To replace values server side, in PHP, you can use switch:
switch ($valueIn) {
case 300: $valueOut = 1; break;
case 600: $valueOut = 2; break;
case 900: $valueOut = 3; break;
default:
// Throw some error, to be warned should you ever change
// the client side array and get an unknown value such as 1200.
}
(or, in this case, also $valueOut = $valueIn / 300).

Post multiple values from database, in one Option

I am looking to populate a drop down field with a list of names from a database, and when an option is selected from that drop down, it will post all its values in the row, belonging to that chosen option.
This is probably hard to describe/understand, so to help illustrate, this is my table row:
I then proceed to populate the dropdown, and associate its value to whatever the selected option is posted
//////db_conx is db connection //////main_meal is table name
<form action="#" method="post">
<?php
$dropdown = $db_conx->query("SELECT * FROM main_meal") or die ("somethings broken");
while($array[] = $dropdown->fetch_object());
//echo '<option value ="'.$record['Mname'].'">'.$record['Mname'].'"</option>';
array_pop($array);
?>
<select name="changeCal">
<?php foreach($array as $option) :?>
<!--//get chosen value in drop down, and get its calories-->
<option value="<?php echo $option->calories;?>"><?php echo $option->Mname; ?></option>
<?php endforeach; ?>
</select>
This works great for one value, such as calories, in the above code, but I need more values.
For example, if choose Healthy egg and chips, the value will post 218, as the loop only associates calories and names at the moment.
I attempted various things, like this post:How to get multiple values from a single <select> variable in HTML/PHP?
But the foreach errors.
How can I something similar to what I have done, but store multiple values from one chosen option?
Thank you
Well, I think I understood your problem, but I think that the way you want to use is not usable, maybe I recommend that you put the id in the value of the option in the < select> and then with php you can get all the data from the data base.
For me that is the best way, but if you want do it like the example that you show, you can make an string, for example:
<option value="id:5_calories:258_protein:11g">Healthy eggs & Chips</option>
with your php should look like:
echo '<option value="id:'.$option->id.'_calories:'.$option->calories.'_protein:'.$option->protein.'">'.$option->Mname.'</option>';
you can make bigger the string with others values that you want to put.
In the backend when you send the select you can catch the data with a:
$myArray = explode("_", $_POST["changeCal"]);
Then you will get an array with values like:
$myArray[0]; // id:5
$myArray[1]; // calories:258
$myArray[2]; // protein:11g
Then if you need for example the calories you can make an explode like:
$calories = explode(":",$myArray[1]);
And you will have:
$calories[0]; //calories
$calories[1]; //258 <= Here are the calories.
Maybe if you want to do it of that way, this can be the easiest way, but I recommend send the ID.
Let me know if you need more help. Regards, Have a nice day.

why select option value if zero post empty

I am sorry bad English. I have a select menu option value problem:
<select>
<option value=0>element1</option>
<option value=1>element2</option>
</select>
I am if select value="0" option and this post, it retuns the value with no problem. But, when I use value = 0 save mysql table, this value not 0 this return empty. This value saving column type integer? What is problem?
I am not using mysql_real_escape_string or any filter. If select value="1" option no problem, it is saving succesfully.
Thanks
I ran into this issue myself and what I found was that when posting option/select box values and reading them with PHP, when the 'value' of it was 0 it was acting like I did not post at all because I was checking to see anything had been posted like this:
if ($_POST['status']) {
// do stuff here
}
When in fact I needed to check it using isset(), because the way shown above returns false even if the value is 0. The example shown below checks to see if it really is set at all, even if the value is 0.
if (isset($_POST['status'])) {
// do stuff here
}
You did not show us your PHP code so I am only guessing this was also your problem.
you missed quotes (")
<select name="my_select">
<option value="0">element1</option>
<option value="1">element2</option>
</select>
<?php
$my_select_value = $_POST["my_select"];
echo $my_select_value;
?>
This one is a pain...no value is sent in the POST if it's a select and the value is 0....so if it's a POST and NOT sent you can assume the value was 0...
if($_POST){
if(isset($_POST['my_select'])){
//has a value, can assume it's 1 given the example
}else {
//posted, but value wasn't sent, can assume it's 0
}
}

Categories