PHP using the select tag - php
I would like help with my homework.
I need to use a select menu and then put the selection of the select tag into a function. Now when I tried doing this I get an undefined error (Which is weird since I did define it) I have tried to do the full if system. But I soon gave up because it was just way to much work, while there is probbaly a better way of doing this.
Here is my code:
<form action=<?php echo $_SERVER['PHP_SELF'];?>>
Vertrek:
<select name="vertrek">
<option value="amsterdam">Amsterdam</option>
<option value="utrecht">Utrecht</option>
<option value="denhaag">Den Haag</option>
<option value="rotterdam">Rotterdam</option>
</select>
Aankomst:
<select name="aankomst">
<option value="amsterdam2">Amsterdam</option>
<option value="utrecht2">Utrecht</option>
<option value="denhaag2">Den Haag</option>
<option value="rotterdam2">Rotterdam</option>
</select>
<br/><br/>
<input type="submit" value="Berekenen">
<p>------</p>
De berekende reiskosten zijn:
<?php
reiskosten(isset($_POST['vertrek']), isset($_POST['aankomst']));
?> Euros's
And the "reiskosten" function:
<?php
function reiskosten($vertrek, $bestemming)
{
$reiskosten = array();
$reiskosten[1] = array();
$reiskosten[2] = array();
$reiskosten[3] = array();
$reiskosten[4] = array();
//Amsterdam naar iets
$reiskosten[1][1] = 0;
$reiskosten[1][2] = 30;
$reiskosten[1][3] = 60;
$reiskosten[1][4] = 90;
//Utrecht naar iets
$reiskosten[2][1] = 30;
$reiskosten[2][2] = 0;
$reiskosten[2][3] = 40;
$reiskosten[2][4] = 20;
//Den Haag naar iets
$reiskosten[3][1] = 60;
$reiskosten[3][2] = 40;
$reiskosten[3][3] = 0;
$reiskosten[3][4] = 10;
//Rotterdam naar iets
$reiskosten[4][1] = 90;
$reiskosten[4][2] = 20;
$reiskosten[4][3] = 10;
$reiskosten[4][4] = 0;
echo($reiskosten[$vertrek][$bestemming] . " Euro's ");
}
?>
The first thing you'll want to fix is that you're calling your reiskosten() function with the wrong arguments. What you mean to do is pass form values to that function, but if you look carefully, you'll see that you're passing the return values of the isset() function, each of which is going to be a boolean (TRUE/FALSE) value, not the value from the form element itself. That said, once you fix that, you'll realize that even the value of the form element is not quite what you'll want either. At that point you'll either adjust what the value="" attributes contain, or re-evaluate the way you're indexing things on the back end. Good luck!
Your values are strings no integers.
$reiskosten[$vertrek][$bestemming] is not defined since its
ie. $reiskosten['rotterdam']['rotterdam2'] is not defined.
You might want to change your array keys to strings or the option value to integers.
your form is GET. You are checking for POST variables.
The isset() function returns true or false, so the following line is incorrect since you appear to want to send the values through:
reiskosten(isset($_POST['vertrek']), isset($_POST['aankomst']));
Change it to:
if( isset($_POST['vertrek']) && isset($_POST['aankomst']) ) {
reiskosten($_POST['vertrek'], $_POST['aankomst']);
}
Also, the values for vertrek and aankomst will be whatever the value field in the HTML option is, so it will be a name, not a number.
You can address it by using associative arrays like:
$reiskosten = array();
$reiskosten['amsterdam'] = array();
$reiskosten['utrecht'] = array();
$reiskosten['denhaag'] = array();
$reiskosten['rotterdam'] = array();
And the same for the sub-array definitions where you set the prices.
Your form should be:
<form action=<?php echo $_SERVER['PHP_SELF'];?>>
Vertrek:
<select name="vertrek">
<option value="1">Amsterdam</option>
<option value="2">Utrecht</option>
<option value="3">Den Haag</option>
<option value="4">Rotterdam</option>
</select>
Aankomst:
<select name="aankomst">
<option value="1">Amsterdam</option>
<option value="2">Utrecht</option>
<option value="3">Den Haag</option>
<option value="4">Rotterdam</option>
</select>
<br/><br/>
<input type="submit" value="Berekenen">
<p>------</p>
De berekende reiskosten zijn:
<?php
$reiskosten = reiskosten($_POST['vertrek'], $_POST['aankomst']);
echo $reiskosten . "Euros's";
?>
option values should (in this instance) be integers.
remove isset() as this only checks if they are set and does not actually return their values.
Create a new variable ($reiskosten) which will be the returned result of the function, and echo it out.
Your PHP should be:
<?php
function reiskosten($vertrek, $bestemming)
{
$reiskosten = array();
$reiskosten[1] = array();
$reiskosten[2] = array();
$reiskosten[3] = array();
$reiskosten[4] = array();
//Amsterdam naar iets
$reiskosten[1][1] = 0;
$reiskosten[1][2] = 30;
$reiskosten[1][3] = 60;
$reiskosten[1][4] = 90;
//Utrecht naar iets
$reiskosten[2][1] = 30;
$reiskosten[2][2] = 0;
$reiskosten[2][3] = 40;
$reiskosten[2][4] = 20;
//Den Haag naar iets
$reiskosten[3][1] = 60;
$reiskosten[3][2] = 40;
$reiskosten[3][3] = 0;
$reiskosten[3][4] = 10;
//Rotterdam naar iets
$reiskosten[4][1] = 90;
$reiskosten[4][2] = 20;
$reiskosten[4][3] = 10;
$reiskosten[4][4] = 0;
$return = $reiskosten[$vertrek][$bestemming];
return $return;
}
?>
No need to echo out here, just return the value.
Related
Delete Blank option Jquery and PHP
I need to remove the blank option. This is a restaurant web page and this is the reservation form. The thing is that they are reciving a lot of "blank" reservation hours because people don't specify the reservation hour. Sorry for my English, I'm from Spain :) The code: HTML read by browser <div id="lashoras"> <select name="Hora" size="1" onChange="updateHoraPersonas();"> <option value="" selected="selected"> </option> <option value="1330">13:30</option> <option value="1400">14:00</option> <option value="1430">14:30</option> <option value="1500">15:00</option> <option value="1930">19:30</option> <option value="2000">20:00</option> <option value="2030">20:30</option> <option value="2100">21:00</option> <option value="2130">21:30</option><option value="2200">22:00</option></select> </div> source code HTML <div id="lashoras"> <?php echo $selectFullDay; ?> SelectFullDay PHP Var $selectFullDay = build_select_options ("Hora","id_lookup","lookup","lookups",0," ",$onChange,$theWhere,$multiple,$orderby); updateHoraPersonas Function function updateHoraPersonas(){ var mediodiaMax = maxPersonas; var nocheMax = maxPersonas; mediodiaMax = maxPersonas-curDia_mediodia_reservados; if(mediodiaMax<0) mediodiaMax = 0; nocheMax = maxPersonas-curDia_noche_reservados; if(nocheMax<0) nocheMax = 0; var hora = $('#lashoras').val(); //hora blank for first, otherwise 1330 //primero ver si llegado a tope de mediodia/noche if (hora <= horaCambio) { selectMax = mediodiaMax; } else { selectMax = nocheMax; } //y ahora hora a hora selectMax = Math.min(selectMax,horasArray[hora]); var Numero_de_personasSelect = ""; for (i=1 ; i<= selectMax ; i++) { if (i==1) { selected = "selected='selected'"; } else { selected = ""; } Numero_de_personasSelect += "<option value='"+i+"' "+selected+" >"+i+"</option>"; } if (selectMax <=0 ) { Numero_de_personasSelect += "<option value=''>Completo</option>"; } $("#Numero_de_personas").html(Numero_de_personasSelect); //alert('mediodiaMax: '+mediodiaMax+' | nocheMax: '+nocheMax+' | selectMax: '+selectMax);} </script> ....
Change the form submission so that the user cannot submit if the reservation time is not specified! This way you processing time does not increase on explicitly removing blank options an exapmle <?php if(!isset($_POST['time'])){ //'Enter valid details }else{ //redirect here }
PHP echo doesn't show up in webpage
So im fairly new in coding HTML CSS and PHP and now im focusing PHP. Our professor asked us to incorporate PHP codes in our website (no database) and im trying to print a an array using a for loop and echo. the problem is that the echo doesn't show in the webpage and I am now lost below is my codes: <html> <head> <title>PHP Loops and Sorts</title> <body> <h1>PHP Loops and Sorts</h1> <div class="container"> <?php $dogs=Array("Labrador Retriever","German Shepherd","Bulldog","Golden Retriever","Poodle","Beagle","Rottweiler","Yorkshire Terrier","Siberian Husky","Dachshund","Chihuahua","Pug","Great Dane","Dobermann","Shih Tzu"); $cats=Array("Persian","Siamese","Maine Coon","Ragdoll","Sphynx","British Shorthair","Abyssinian","Bengal","Scottish Fold","Himalayan","Russian Blue","Siberian","Munchkin"); $birds=Array("Canaries","Budgies","Finches","Cockatiels","Quaker Parakeets","Pionus Parrots","Poicephalus Parrots","Amazon Parrots","Pyrrhura Conures","Peach-Faced Lovebirds"); $fishes=Array("Koi","Fantail","Oranda","Comet","Black Telescope","Butterfly Tail","Ryukin","Goldfish","Lionhead","Mirror Carp"); function countsize($array,$size){ $size = count($array); return $size; } if(isset($_POST['btnShow']) ) { $arraypick=$_POST['formAnimal']; $arrsize = countsize($arraypick,$size); for(&x = 0,$x<$arrsize,$x++){ echo $arraypick[$x] . "<br>"; } } ?> Breeds of different kinds of animals. Select what animal's breed to be shown:<br> <select name="formAnimal"> <option value="">Choose animal</option> <option value="dogs">Dog</option> <option value="cats">Cat</option> <option value="birds">Bird</option> <option value="fishes">Fish</option> </select><br><br> <div style="margin:auto,text-align:center;text-align:center"> <INPUT TYPE = "Submit" Name = "btnShow" VALUE = "Show List"> <INPUT TYPE = "Submit" Name = "btnAsc" VALUE = "Show Ascending"> <INPUT TYPE = "Submit" Name = "btnDes" VALUE = "Show Descending"> </div> <?php echo $size ?> </div> </body> </html>
You need to close your head tag before your body tag. You also don't need to pass in size to your method count size. function countsize (&array) { return count(&array); }
if(isset($_POST['btnShow']) ) are you sure it is set ? From what we have in your code you can't even POST, you are missing your form tags Try wrapping your inputs with : <form method="POST"> <!--inputs--> </form>
Your syntax for the for loop is incorrect. Check out the php documentation Also the $size variable is never declared in the scope you are using it.
Didn't get how you're using $arrsize but you used &x instead of $x while initializing loop. for($x = 0,$x<$arrsize,$x++){ echo $arraypick[$x] . "<br>"; }
change this lines of code: $dogs=Array("Labrador Retriever","German Shepherd","Bulldog","Golden Retriever","Poodle","Beagle","Rottweiler","Yorkshire Terrier","Siberian Husky","Dachshund","Chihuahua","Pug","Great Dane","Dobermann","Shih Tzu"); $cats=Array("Persian","Siamese","Maine Coon","Ragdoll","Sphynx","British Shorthair","Abyssinian","Bengal","Scottish Fold","Himalayan","Russian Blue","Siberian","Munchkin"); $birds=Array("Canaries","Budgies","Finches","Cockatiels","Quaker Parakeets","Pionus Parrots","Poicephalus Parrots","Amazon Parrots","Pyrrhura Conures","Peach-Faced Lovebirds"); $fishes=Array("Koi","Fantail","Oranda","Comet","Black Telescope","Butterfly Tail","Ryukin","Goldfish","Lionhead","Mirror Carp"); function countsize($array,$size){ $size = count($array); return $size; } $arraypick=$_POST['formAnimal']; $arrsize = countsize($arraypick,$size); for(&x = 0,$x<$arrsize,$x++){ echo $arraypick[$x] . "<br>"; } To : $animalArray['dogs']=Array("Labrador Retriever","German Shepherd","Bulldog","Golden Retriever","Poodle","Beagle","Rottweiler","Yorkshire Terrier","Siberian Husky","Dachshund","Chihuahua","Pug","Great Dane","Dobermann","Shih Tzu"); $animalArray['cats']=Array("Persian","Siamese","Maine Coon","Ragdoll","Sphynx","British Shorthair","Abyssinian","Bengal","Scottish Fold","Himalayan","Russian Blue","Siberian","Munchkin"); $animalArray['birds']=Array("Canaries","Budgies","Finches","Cockatiels","Quaker Parakeets","Pionus Parrots","Poicephalus Parrots","Amazon Parrots","Pyrrhura Conures","Peach-Faced Lovebirds"); $animalArray['fishes']=Array("Koi","Fantail","Oranda","Comet","Black Telescope","Butterfly Tail","Ryukin","Goldfish","Lionhead","Mirror Carp"); function countsize($index){ return count($animalArray[$index]); } $arraypick=$_POST['formAnimal']; $arrsize = countsize($arraypick); for($x = 0;$x<$arrsize;$x++){ echo $animalArray[$arraypick][$x] . "<br>"; }
PHP array sort / select option form
I have a form in PHP. It is unsorted. I would like to sort it. How would I go by it. This is the following PHP code I have. Thanks for help in advance. <select id="school_name" name="school_name"> <option value="">Select School</option> <?php for($c=0; $c<sizeof($school_details); $c++){?> <option value="<?php echo stripslashes($school_details[$c]["title"]); ?>" <?php if($school_details[$c]["title"]==$appInfo["school_name"]){?> selected="selected" <?php } ?> ><?php echo stripslashes($school_details[$c]["title"]); ?> </option> <?php } ?> </select>
try somthing like this: $str = "<select id='school_name' name='school_name'>"; $options = ""; for($i = 0; $i<10;$i++) { $RandomNum = rand(0, 100); $options = "" . $options . ("<option value='$RandomNum'> " . $RandomNum . "  </option>\n"); } $optionsArray = explode("\n", $options); natsort($optionsArray); $sorted_option = implode("|",$optionsArray); $select = $str.$sorted_option."</select>"; echo $select;
PHP provides a number of methods for sorting: http://www.php.net/manual/en/array.sorting.php
You could implement a user defined sort to achieve this. Assuming you want to sort by the value of the 'title' element you would simply add this before your opening select tag: <?php uasort($school_details,'cmp'); function cmp($a,$b){ if($a['title'] == $b['title']){return 0;} return ($a['title'] < $b['title']) ? -1 : 1; } ?>
HTML/PHP - form selection box greater than database value, increment by 500 in each selection value
I am trying to create something similar to an auction/bidding table/form. If a value (current bid) is 1000, I am trying to create a selection box that allows another user to bid in intervals of 500, so for this example the outcome would be like: Current Bid: 1000 Buy Now: 5000 <select class="form-control"> <option value="1500">1500</option> <option value="2000">2000</option> <option value="2500">2500</option> <option value="3000">3000</option> <option value="3500">3500</option> <option value="4000">4000</option> <option value="4500">4500</option> </select> Something like this: <?php $query = $db->query('SELECT * FROM auctions WHERE available = 1 LIMIT 1'); $num = $query->num_rows; if($num > 0) { echo '<select class="form-control">'; foreach($query as $row) { $currentBid = $row['currentBid']; // 1000 $buyNow = $row['buyNow']; // 5000 $bids = ?? // this is where I am stuck, how can I make the difference between $currentBid and $buyNow show as options divided by 500's echo ' <option value="'.$bids.'">'.$bids.'</option> '; } echo '</select>'; } else { echo "No auctions available"; } ?>
... $currentBid = $row['currentBid']; $buyNow = $row['buyNow']; ... $options = ''; for($p = $currentBid + 500; $p <= $buyNow; $p += 500) { $options .= '<option value="'.$p.'">'.$p.'</option>'; }
Array doesn't appear to be holding data
I have a system where I rearrange navigational items. It stores the new order in an array and then I use a for loop to go through the array and update the database. <?php $apageid = array(); $apagename = array(); $apageorder = array(); $q = "SELECT g.id, g.title, n.order FROM tbl_general g INNER JOIN tbl_navigation n ON n.pageid = g.id WHERE n.type = '$_SESSION[parent]' ORDER BY n.order"; $return = $database->query($q); while($row=mysql_fetch_assoc($return)){ $apageid[] = $row['id']; $apagename[] = $row['title']; $apageorder[] = $row['order']; } $count = count($apageid); $bpageid = array(); $bpageorder = array(); ?> <div class="form-holder"> <?php //run through each page one at a time and update the order of the menu mysql_data_seek( $return, 0 ); //reset the pointer to do the same query $i = 0; //the count for saving the new configuration while($row=mysql_fetch_assoc($return)){ $id = $row['id']; $title = $row['title']; $order = $row['order']; ?> <div class="form-row"> <div class="form-label"> Page Name </div> <div class="form-field"> <select class="select-small" name="<?php echo $bpageid[$i]; ?>"> <?php for($j=0; $j<$count; $j++){ if($apageid[$j] == $id) { $selected = true; } else { $selected = false; } ?> <option value="<?php echo $apageid[$j]; ?>" <? echo ($selected == true) ? 'selected="selected"' : ''; ?>><?php echo $apagename[$j]; ?></option> <?php } ?> </select> <select class="select-small" name="<?php echo $bpageorder[$i]; ?>"> <?php for($k=0; $k<$count; $k++){ if($apageorder[$k] == $order) { $selected = true; } else { $selected = false; } ?> <option value="<?php echo $apageorder[$k]; ?>" <? echo ($selected == true) ? 'selected="selected"' : ''; ?>><?php echo $apageorder[$k]; ?></option> <?php } ?> </select> </div> </div> <?php $i++; } ?> This first chunk of code is the menu where you can reorder items. Initially it loads up the current select and allows you to change the ordering. function reorderChildren($pageid, $pageorder){ global $database; $count = count($pageid); //run through each page one at a time and update the order of the menu for($i=0; $i<$count; $i++){ //set a few variables $pid = $pageid[$i]; $porder = $pageorder[$i]; echo "pid = $pid porder = $porder"; $q = "UPDATE tbl_navigation SET order = '$porder' WHERE pageid = '$pid' AND type = '$_SESSION[parent]'"; $database->query($q); } return 0; } The information then ends up being passed here and the problem appears to be the for loop is never executed. Can anyone see why this would be? It's not the naming used, I've checked them. Am I storing information in the arrays correctly? Can I make it clear that it's $bpageid and $bpageorder that are the arrays carrying the information forward. Thanks!
Was a simple fix! The problem was that the select name needed to be just name="bpageid[]" rather than what I listed above. Silly!
You have just initilized $bpageid = array(); at top after first while loop.No value is assigned after that you using <select class="select-small" name="<?php echo $bpageid[$i]; ?>"> but no value is in $bpageid[$i] so name of this select box is blank. It might be problem. check this and do as required.
you could try to construct a json from the options of the select element store it to a hidden field or send ajax request to php script for processing , order could be made from a "weight" value 1,2,3 etc.... sort it with php and loop to display