php if statement html option value - php

Suppose you have the following html select statement
<select>
<option value="Newest">Newest</option>
<option value="Best Sellers">Best Sellers</option>
<option value="Alphabetical">Alphabetical</option>
</select>
Now I want to run a php if elseif statement that says,
if (option value = newest) {
// Run this
}
elseif ( option value = best sellers ) {
// Run this
}
etc. But I don't know what to put inside the if elseif statement. In other words instead of 'option value = newest' (which I know is incorrect), what can I put there so that if newest is selected it will execute the if statement, or if best sellers is selected it will execute the elseif statement?

Give name to your select.
<select name="selectedValue">
<option value="Newest">Newest</option>
<option value="Best Sellers">Best Sellers</option>
<option value="Alphabetical">Alphabetical</option>
</select>
in your PHP, you will do:
$_POST['selectedValue'];
if I were you, I would prefer a switch-case incase, there are more than 2 conditions.
Example:
switch($_POST['selectedValue']){
case 'Newest':
// do Something for Newest
break;
case 'Best Sellers':
// do Something for Best seller
break;
case 'Alphabetical':
// do Something for Alphabetical
break;
default:
// Something went wrong or form has been tampered.
}

First put a name on your select:
<select name="demo">
<option value="Newest">Newest</option>
<option value="Best Sellers">Best Sellers</option>
<option value="Alphabetical">Alphabetical</option>
</select>
Then
if ($_POST['demo'] === 'Newest') {
// Run this
}
elseif ( $_POST['demo'] === 'Best Sellers' ) {
// Run this
}
or
switch($_POST['demo']){
case 'Newest' :
//some code;
break;
case 'Best Sellers':
//some code;
break;
default:
//some code if the post doesn't match anything
}

The <select> should have a name attribute, e.g <select name="sortorder">. You could then say
if ($_REQUEST['sortorder'] == 'Newest') {
// TODO sortorder 'Newest' was selected.
}
If you know whether the form data is comming in via HTTP GET or HTTP POST, you could use $_GET['sortorder'] or $_POST['sortorder'] respectively.

I think the read-friendly version would be:
switch($option){
case 'Newest':
runNewestFunction();
break;
case 'Best Sellers':
runBestSellersFunction();
break;
case 'Alphabetical':
runAlphabeticalFunction();
break;
default:
runValidationRequest();
}
also, please add the name attribute <select name="option">

Related

PHP Setting select as variable

How can i make piece of select statement as php variable?
Example:
I have 2 options in select statement - edit and delete... I have those 2 options in dropdown menu... I want to make an mySQL query to edit or delete records/users from database...I tried to use switch and cases but it only gave me default as selecting.
<select name="editSelector">
<option name='edit'>Edit</option>
<option name='delete'>Delete</option>
</select>
<?php
if (select == edit)
{
edit query here
}
elseif (select == delete)
{
delete query here
}
?>
I know that this code doesn't have any variables etc. Because i have no idea how to make option as variable. It's connected to database already. Thanks for the answer in advance.
<?php
if($_REQUEST['editSelector'] == "edit"){
edit here;
}
else if ($_REQUEST['editSelector'] == "delete"){
delete here;
}
?>
Plus :
<select name="editSelector">
<option value='edit'>Edit</option>
<option value='delete'>Delete</option>
</select>
you need to place your select > option list in a form and process it the proper way using POST.
I would strongly advise against using ajax to facilitate any crud activity in your database. Unless you know what youre doing its VERY insecure.
heres a reasonable web resource if you need to look things up.
HTML file
<form name='option_form' action='someProcessingFile.php' method='post'>
<select name="editSelector">
<option value='edit'>Edit</option>
<option value='delete'>Delete</option>
</select>
<input type='submit' name='submit' value='Submit'/>
</form>
someProcessingFile.php
<?php
if(isset($_POST['editSelector']) {
switch($_POST['editSelector']) {
case 'edit':
// do something here, probably with the rest of the form
break;
case 'delete':
$id = htmlspecialchars($_POST['id']);
// do something here and delete the entry
break;
default:
// do something here to let yourself know that it all went wrong for some reason.
}
}

correct syntax for php switch case statement when using arrays and adding elements to a different array

Could you please help me find the correct syntax for putting a switch statement on an array, then on each case, add an element to a new array.
I have a 2-step form (which is actually 2 forms using the same php file). On the first form, the user enters food names, chooses whether they want to use grams or cups as the serving size, and they choose a daily or weekly calculation.
Once the first form is submitted, matches to their foods are retrieved from the database and displayed in form #2 with a checkbox next to the food name. They can unselect any matches they don't want. This all works fine.
Upon submitting the second form, the amount of Vitamin C is calculated by pulling the amount of Vitamin C in each food from the database, in either grams or cups. The php code calculates the amount of vitamin C based on what serving size they select (there are many options for grams and many options for cups). This is the switch statement that I can't figure out.
Form #2 is:
<!--START DISPLAY OF FORM 2-->
<div class="step2">
<div class="row">
<h2>Step 2 of 2</h2>
</div>
<div class="row"> <h3>We Found these matching foods. </h3> <ol><li><h4>Uncheck the ones you don't want to include in your calculation.</h4></li><li><h4>Enter your serving size. If daily, enter amount of each food you feed your guinea pig each day. If weekly, enter total amounts that you give him each week.</h4></li><li><h4>Click "Calculate my Vitamin C".</h4></li></ol></div>
<form id="step2" class="form-horizontal" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
<?php if ($servingsize == "grams") {
foreach ($results as $CurRes) {
echo '<div class="row">' . '<div class="col-sm-1">' . '<input type="checkbox" name="foodname[]" ' . 'value="'.$CurRes['name'].'"' . 'checked>'. '</div>' . '<div class="col-sm-2">' .$CurRes['name'] .'</div>' . '<div class="col-sm-9">'; ?>
<fieldset>
<!-- Select Basic -->
<div class="control-group">
<label class="control-label" for="amountg">Amount</label>
<div class="controls">
<select id="amountg" name="amountg[]" class="input-medium">
<option value="10">10g</option>
<option value="20">20g</option>
<option value="30">30g</option>
<option value="40">40g</option>
<option value="50">50g</option>
<option value="60">60g</option>
<option value="70">70g</option>
<option value="80">80g</option>
<option value="90">90g</option>
<option value="100">100g</option>
<option value="110">110g</option>
<option value="120">120g</option>
<option value="130">130g</option>
<option value="140">140g</option>
<option value="150">150g</option>
<option value="160">160g</option>
<option value="170">170g</option>
<option value="180">180g</option>
<option value="190">190g</option>
<option value="200">200g</option>
</select>
</fieldset>
</div><!--end of div class controls-->
</div><!--end of div class control-group-->
</div><!--end of div class-col-sm-9-->
</div><!--end of div class=row-->
<?php } //end of foreach
} else /*end of if servingsize="grams"*/ {
foreach ($results as $CurRes) {
echo '<div class="row">' . '<div class="col-sm-1">' . '<input type="checkbox" name="foodnames[]" ' . 'value="'.$CurRes['name'].'"' . 'checked>'. '</div>' . '<div class="col-sm-2">' .$CurRes['name'] .'</div>' . '<div class="col-sm-9">'; ?>
<fieldset>
<!-- Select Basic -->
<div class="control-group" style="display:inline">
<label class="control-label" for="cups">Amount</label>
<div class="controls" style="display:inline">
<select id="cups" name="cups" class="input-medium">
<option value="1/4">1/4 cup</option>
<option value="1/2">1/2 cup</option>
<option value="3/4">3/4 cup</option>
<option value="1">1 cup</option>
<option value="1 1/4">1 1/4 cups</option>
<option value="1 1/2">1 1/2 cups</option>
<option value="1 3/4">1 3/4 cups</option>
<option value="2">2 cups</option>
<option value="2 1/4">2 1/4 cups</option>
<option value="2 1/2">2 1/2 cups</option>
<option value="2 3/4">2 3/4 cups</option>
<option value="3">3 cups</option>
</select>
</div><!--end of div class controls-->
</div><!--end of div class control-group-->
</div><!--end of div class col-sm-5-->
</div><!--end of div class row-->
</fieldset>
<?php } /*end of foreach*/
} /* end of else - (is cups)*/ ?>
<p><input type="submit" value="Calculate my Vitamin C" name="form2"></p>
</form>
</div><!--end of <div class="step2">-->
<!--END STEP 2-->
The switch statement is:
/*GOAL HERE IS: take the amount they selected on the form and convert the mysql results based on serving size. For example, if they selected 50 grams, that's .5 * $curRes['mgc100g']*/
if (isset($_POST['form2'])) {
if ($servingsize == "grams") {
foreach ($_POST['foodname'] as $value) {
$vitc=array();
switch ($value) {
case "10":
$vitc[] = $curRes['mgc100g']/10;
break;
case "20":
$vitc[] = $curRes['mgc100g']/5;
break;
case "30":
$vitc[] = $curRes['mgc100g']/3.3333;
break;
case "40":
$vitc[] = $curRes['mgc100g']/2.5;
break;
case "50":
$vitc[] = $curRes['mgc100g']/2;
break;
case "60":
$vitc[] = $curRes['mgc100g']/1.667;
break;
case "70":
$vitc[] = $curRes['mgc100g']/1.4286;
break;
case "80":
$vitc[] = $curRes['mgc100g']/1.25;
break;
case "90":
$vitc[] = $curRes['mgc100g']/1.1111;
break;
case "100":
$vitc[] = $curRes['mgc100g'];
break;
case "110":
$vitc[] = $curRes['mgc100g']*1.1;
break;
case "120":
$vitc[] = $curRes['mgc100g']*1.2;
break;
case "130":
$vitc[] = $curRes['mgc100g']*1.3;
break;
case "140":
$vitc[] = $curRes['mgc100g']*1.4;
break;
case "150":
$vitc[] = $curRes['mgc100g']*1.5;
break;
case "160":
$vitc[] = $curRes['mgc100g']*1.6;
break;
case "170":
$vitc[] = $curRes['mgc100g']*1.7;
break;
case "180":
$vitc[] = $curRes['mgc100g']*1.8;
break;
case "190":
$vitc[] = $curRes['mgc100g']*1.9;
break;
case "200":
$vitc[] = $curRes['mgc100g']*2;
break;
default:
echo "We couldn't calculate that. Sorry!";
}//end of switch statement
return $vitc;
} //end of foreach loop
} else { //end of if $servingsize == grams
foreach ($_POST['foodnames'] as $values) {
$vitcc = array();
switch ($value) {
case "1/4":
$vitcc[] = $curRes['mgc1cup']/4;
break;
case "1/2":
$vitcc[] = $curRes['mgc1cup']/2;
break;
case "3/4":
$vitcc[] = $curRes['mgc1cup']/1.3333;
break;
case "1":
$vitcc[] = $curRes['mgc1cup'];
break;
case "1 1/4":
$vitcc[] = $curRes['mgc1cup']*1.25;
break;
case "1 1/2":
$vitcc[] = $curRes['mgc1cup']*1.5;
break;
case "1 3/4":
$vitcc[] = $curRes['mgc1cup']*1.75;
break;
case "2":
$vitcc[] = $curRes['mgc1cup']*2;
break;
case "2 1/4":
$vitcc[] = $curRes['mgc1cup']*2.25;
break;
case "2 1/2":
$vitcc[] = $curRes['mgc1cup']*2.5;
break;
case "2 3/4":
$vitcc[] = $curRes['mgc1cup']*2.75;
break;
case "3":
$vitcc[] = $curRes['mgc1cup']*3;
break;
default:
echo "We couldn't calculate that. Sorry!";
}//end of switch statement
return $vitcc;
} //end of foreach loop
} //end of else statement (i.e., $servingsize is cups)
} //end of if isset($_POST('form2'))
/*ADD TOTAL OF VITAMIN C mg*/
if ($_POST['radios'] == "grams") {
foreach ($vitc as $amount) {
$totalvitcgrams = round(array_sum($vitc), 1);
return $totalvitcgrams;
} //end of foreach
} elseif ($_POST['radios'] == "cups") { //end of if $_POST['amountg'] == grams
foreach ($vitcc as $amounts) {
$totalvitccups = round(array_sum($vitcc), 1);
return $totalvitccups;
} //end of foreach
} /* end of elseif ($_POST['amountg'] != grams*/ else {
echo 'An error occurred. Sorry!'; }
//Calculate daily amount of Vitamin c from weekly totals
if ($weekly == "true") {
$weektodaygrams = $totalvitcgrams/7;
$weektodaycups = $totalvitccups/7;
}//end of if $weekly == true
?>
I get "Error: Invalid argument supplied for foreach() on line 320)" which is "return $totalvitccups;"
$curRes['mgc1cup'] is the data pulled from the database.
I've tried everything I can think of for two days and I still can't get it to work.
So I have an array from the form called foodname[]. I need to go through each submitted foodname, and if it's there, do a calculation on it based on selected serving size, and then stick the result into an array, which I've named vitc (for grams) and vitcc (for cups).
I've done a var_dump on everything and put it in several places in the code, but I nothing gets displayed. The only error I get is the invalid argument, which isn't helping me much.
So how can I take each calculation in each case of the switch statement and add it onto an array? Because after I have the array, I will add all values in the array together to get the total amount. Getting the array is the problem.
The entire code is long, but if you want to see, it is here. The field forms can go from 1-20 fields for the food names (dynamically populated with javascript).
If you need to see it with the javascript enabled, it's here (enter 'hello').
My coding is not great. I read 3 books on php and completed 2 online courses for php, but yet when I sit down to code, I have major problems getting stuff to do what I want it to. But I keep trying and trying and trying. But this time I'm really stuck.
First off,
$vitc = array();
&
$vitcc = array();
both need to be outside your foreach (above), else they will get recreated each iteration and only contain the last value.
Second, regarding the error you're getting,
return $totalvitcgrams;
&
return $totalvitccups;
both of these also need to be outside the foreach loops (below)
And keep in mind the variable names you use, as #Sumurai8 said in the comments, you're using the wrong variable name $values vs $value
Also, you need to remove
return $vitc;
&
return $vitcc;
from the end of your switch.
You could also, very simply, simplify this by doing something like:
$vitc = array();
foreach($_POST['foodnames'] as $value){
$vitc[] = $curRes['mcg100g'] / (100 / $value);
}
no need for a switch statement like this.
Or in your <option> tag just supply the correct value. The value doesn't have to match the text of the option. That would also alleviate the need for such a cumbersome switch and leave you with a simply foreach loop

Error while getting select box value with php

I am currently working on a project where a user chooses an option from a select box and submits a form, the form is then processed by PHP, and the PHP code determines what the select box value is, and does something based on that value.
My select box is called combined_group and has two select values: philharmonic_orchestra and symphony_orchestra.
This is how I am checking the selected value:
if($_POST['combined_group'] == "philharmonic_orchestra"){
$_SESSION['semesterprice'] = "170";
$_SESSION['fullprice'] = "330";
}
if($_POST['combined_group'] == "symphony_orchestra"){
$_SESSION['semesterprice'] = "275";
$_SESSION['fullprice'] = "530";
}
But when PHP runs through this code, neither if statement is chosen. I know that the value of $_POST['combined_group'] is, in fact, either of those two values, just PHP isn't picking it up for some reason.
Anybody care to help?
EDIT: My HTML form code is as follows
<select name="combined_group" class="OBJ-1">
<option value="" selected="">Select One</option>
<option value="philharmonic_orchestra">Philharmonic Orchestra</option>
<option value="symphony_orchestra ">Symphony Orchestra</option>
</select>
Client side
<select name="combined_group">
<option value="">Select an option</option>
<option value="philharmonic_orchestra">Philharmonic Orchestra</option>
<option value="symphony_orchestra">Symphony Orchestra</option>
</select>
Server side
if (! isset($_POST["combined_group"]))
{
exit('not set');
}
if (trim($_POST["combined_group"]) == '')
{
exit('not selected');
}
if (trim($_POST["combined_group"]) == 'philharmonic_orchestra')
{
//business logic for 'philharmonic_orchestra'
}
else
{
//business logic for 'symphony_orchestra'
}
Most likely is a bad HTML syntax. Check if your option item has value attribute:
<option value="...">...</option>
The reason why your conditional statement is failing, is because of a space in your option's value.
<option value="symphony_orchestra ">
^ right there
What you will need to do is remove it:
<option value="symphony_orchestra">
^ deleted space
Technical sidenote:
Had your conditional statement been:
if($_POST['combined_group'] == "symphony_orchestra ")
^ notice the space
with the space before the quote, it would have worked.
Anything between quotes is considered and part of an element's value.

load select box with a selected option using php

Hi I have come across a problem now I do have a solution however it involves many of if statements and I would like to know it there is a neater option
what I would like is
<select>
<option value ="00:00">00:00</option>
<option value ="01:00">01:00</option>
<option value ="02:00">02:00</option>
<option value ="03:00">03:00</option>
</select>
then get an value from and have that box selected
what I'm am currently thinking is
$selectedbox = array();
if($tablevalue == "00:00"){
$selectedbox[0] = 'selected="selected"';
}
if($tablevalue == "01:00"){
$selectedbox[1] = 'selected="selected"';
}
then have
<select>
<option value ="00:00" <?php echo $selectedbox[0]; ?>>00:00</option>
<option value ="01:00" <?php echo $selectedbox[1]; ?>>01:00</option>
<option value ="02:00" <?php echo $selectedbox[2]; ?>>02:00</option>
<option value ="03:00" <?php echo $selectedbox[3]; ?>>03:00</option>
</select>
is there an easier way of getting the same result
for ($i = 0; $i <= 3; $i++) {
$sel = ("0{$i}:00" == $tablevalue) ? ' selected="selected"' : '';
echo <<<EOL
<option value="0{$i}:00"{$sel}>0{$i}:00</option>
EOL;
}
I would get rid of the if statements and put the code inline with the option tag with a ternary. Ex:
<select>
<option value ="00:00" <?=$tablevalue=="00:00"?'selected="selected"':''?>>00:00</option>
<option value ="01:00" <?=$tablevalue=="01:00"?'selected="selected"':''?>>01:00</option>
<option value ="02:00" <?=$tablevalue=="02:00"?'selected="selected"':''?>>02:00</option>
<option value ="03:00" <?=$tablevalue=="03:00"?'selected="selected"':''?>>03:00</option>
</select>
Take a look at PHP switch statements: http://php.net/manual/en/control-structures.switch.php
I think you would want something like this:
switch ($tablevalue) {
case "00:00":
$selectedbox[0] = 'selected="selected"';
break;
case "01:00":
$selectedbox[0] = 'selected="selected"';
break;
//etc, etc
}
PHP switch is a better way to handle if statements if you're always comparing the same variable.

Error javascript function to get value out of static php drop down

I made the dropdown with PHP which works fine. When the selected item changes, I call the function changePeriod().
$options[0] = '--period--';
$options[1] = 'Daily';
$options[2] = 'Weekly';
$options[3] = 'Monthly';
<td><?php echo form_dropdown('period', $options, '0', 'id="period" onchange="changePeriod()"'); ?></td>
Here you can see the HTML source code which is a result of the code above.
<td>
<select name="period" id="period" onchange="changePeriod()">
<option value="0" selected="selected">--period--</option>
<option value="1">Daily</option>
<option value="2">Weekly</option>
<option value="3">Monthly</option>
</select>
</td>
In this function I need to get the value of the selected item, but the 2 alerts above the switch both give Undefined as a result. Does anyone has an idea why I get undefined and not the values of the selected option? It worked with a dynamic dropdown filled with a foreach from the database.
function changePeriod() {
alert(document.getElementById("period").selectedIndex);
alert(document.getElementById("period").value);
switch (document.getElementById("period").selectedIndex) {
case 1:
alert("daily");
break;
case 2:
alert("weekly");
break;
case 3:
alert("monthly");
break;
}
}
Basically: Why can't I get the values of the selected option and how can I fix it?
Thanks for helping.
Is the HTML generated like this:
<select onchange="changePeriod()" id="period">
<option value="0">--period--</option>
<option value="1">Daily</option>
<option value="2">Weekly</option>
<option value="3">Monthly</option>
</select>
<script type="text/javascript">
function changePeriod(event) {
alert(document.getElementById("period").selectedIndex);
alert(document.getElementById("period").value);
switch (document.getElementById("period").selectedIndex) {
case 1:
alert("daily");
break;
case 2:
alert("weekly");
break;
case 3:
alert("monthly");
break;
}
}
</script>
If yes, it works for me.
Why don't you use jquery, you could do everything with less code.
EDIT:
The solution with jQuery:
$("#period").change(function(){
alert("The Value: "+$(this).val());
switch ($(this).val()) {
case 1:
alert("daily");
break;
case 2:
alert("weekly");
break;
case 3:
alert("monthly");
break;
}
});
take a look here: http://jsfiddle.net/rfWjd/

Categories