Choosing a value in a drop down box based on database query - php

I basically need to create a value by default for a drop down menu on a PHP page that will use the value previously selected and stored in the database.
For example, lets just say I have the value '3' stored in a database column. I want to use this number as the default value for a drop down menu where the <option value = "3">Good</option>. Is there a simple solution to this problem?
Or do i literally need to loop through the values until it makes a value?
Thanks.

I usually do this
<?php
$sel = 'selected="selected"';
$current_whatever = 5;
?>
<option name="whatever">
<?php foreach($list as $listItem): ?>
<option value="<?=$listItem->id?>" <?=($listItem->id == $current_whatever)?$sel:''?>><?=$listItem->name?></option>
<?php endforeach; ?>
</option>
I'm using an inline if statement to check each one :) Looks reasonably tidy.
Assuming you're using database objects, you get the idea if you're not though :)

<?php foreach($options as $key=>$option){?>
<option value='<?=$key?>' <? echo $key==$selected?"SELECTED":"";?> ><?=$option?></option>
<? }?>

Related

issue with IF statement returning unexpected result

I am trying to achieve the following...
Each 'element' should have the option to choose one 'sibling' from a select dropdown, the siblings are chosen from all of the other elements, the sibling cannot be itself, but a sibling doesn't have to be assigned. If one is assigned it should be selected by default in the select list.
<?php echo $sibling; ?>
<select name="sibling">
<option value="none">none</option>
<?php
while($row = $result->fetch_array()) {
if($row['element']!=$element){
echo '<option value="'.$row['element'].'" ';
if($row['sibling']==$sibling){
echo 'selected="selected"';
}
echo '>'.$row['element'].'</option>';
}
}
?>
</select>
I have almost achieved what I want but for some reason the code doesn't add selected="selected" to the right option.
I'd appreciate any guidance anyone could give in where I may be going wrong? I'm fairly new to PHP so I may be going about this in the wrong way.
$element and $sibling are equal to $row['element'] and $row['sibling'] for the corresponding $id which is an index that is passed to the page on a query string.
UPDATE: FOUND ANSWER
So with a little investigation this was glaringly obvious.
The line containing...
if($row['sibling']==$sibling)
should have been...
if($row['element']==$sibling){
Thanks to #RyanS for suggesting the var dump.

dynamic html select boxes need to update mysql

Ok, so this one is a little confusing. I have select dropdowns that are produced by PHP. It can be 4 selects, or 30 select dropdowns. Then there's option values. Here's what I have so far
<?php while($row = mysql_fetch_assoc($notes)){ ?>
<select name="milestone" id="milestone[<?php echo $row['id']; ?>]">
<option value="Enrollment Date">Enrollment Date</option>
<option value="Discharge Date">Discharge Date</option>
<option value="A/C Start">A/C Start</option>
<option value="Completion Date">Completion Date</option>
</select>
<?php } ?>
If I have 4 select boxes, I might have arrays as follows: milestone[2134], milestone[2222], milestone[225], and milestone[1022]
The array number is the id of the mysql table entry I need to update with the value of that specific select dropdown. I was thinking maybe to use milestone[][id] and loop through that?
Any ideas since there might be 20 select dropdowns?
Thanks!
do you want to fetch the values of your options from the database as well as the id ? Then you should to mysql_fetch_array or mysql_fetch_object function instead of mysql_fetch_assoc. This function only returns the number of the results while the two above returns the number as well as values.
Got it!
First, I had to apply the array to the name of the select like so and set the id value:
<select name="milestone[]" class="mstones" id="<?php echo $row['session_id']; ?>">
Then, with jquery, looped through the class and created created an array with the value being something I can "explode" in php:
var milestoneVal = [];
$("select.mstones").each(function(i, selected){
milestoneVal[i] = this.getAttribute('id') + ':' + $(selected).val();
});
Then, simple PHP
foreach($_POST['milestone'] as $v){
$m=explode(':',$v);
//db insert
}
It was tricky, and I'm sure there's a cleaner solution, but it works for me! Sorry for the poor initial explanation, and hope this helps someone else.

How to get the value and id from a drop down in php?

I have created and html form which have a drop down list.
This drop down list is populated from database.
<select name="classes">
<?php
foreach() {
?>
<option value="<?php echo $id ?>"><?php echo $name ?></option>
<?php
}
?>
</select>
Now I want to get the $id and $name both. How will I do this?
I have tried this
echo $_POST['classes'];
But it only displays the $id of the select item. And I want $id and $name both.
You can't. One possibility would be placing both infos inside the value attribute, and then separating them back again with php (by using a delimiter):
<option value="<?php echo $id.'|'.$name; ?>"><?php echo $name ?></option>
In PHP:
$datas = explode('|',$_POST['classes']);
$id = $datas[0];
$name = $datas[1];
But that's not how the system is meant to be. Usually the $name would be used only as a "friendly" info for the user, cause the value might sometimes just be an INT and user won't understand what that int refers to, so we give him a word description in order to choose an option: but what you would only care of is that value indeed, which you can always use to get again the description that comes along with it (by a search to the database, for ex.)
As far as I know, when you submit that form, only the value is going to be carried over. If there is no value then the inner HTML becomes the value.
What I'd do is:
<select name="classes">
<?php
foreach($classes as $id => $name) //i'm guessing here, is this what you meant?
{ ?>
<option value="<?php echo $id.'|'.$name ?>"><?php echo $name ?></option>
<?php } ?>
</select>
In case you are not familiar, the period is the concatenation operator. Think of it as glue for pieces of a string. So I'm gluing $id to the left of "pipe" and then gluing $name onto the end of that.
Then in your handler, use split or explode to separate the two values on the pipe.
Actually, I'd do it a little different, echoing more and going in and out of php/html less, but I tried to leave your code intact as much as possible.
append name to Id and pass it as value,,and explode name from the other end
You want is and name both so while storing option value ,
put like this
<option value="<?php echo $id."_".$name;?>"><?php echo $name?></option>
and on posting data just explode the value you will get both is and name
Sending form means only sending 'value' for select field (treat 'name' in option as a label only). You can simply fetch 'name' from database when you have 'id' while handling form submission.

getting default value of dropdown box html in php loop

So I have this problem, which I don't see how it's happening. Basically I have 2 arrays one of which has a list of apparatus and the other just has one apparatus that the user can operate. I want to have a dropdown list of all the apparatus avliable, but the default value that is selected is the one that they can operate (They can only operate one at a time) Here is the code, and I have an if statement to check if the user can operate it and selected = "selected" but that doesn't seem to be working (In firefox)... Any help would be great.
Thanks!
<?php
foreach ($apparatuslist as $apparatus):?>
<option value="<?php echo $apparatus['apparatus'];?>" <?php if ($driveron['apparatus'] == $apparatus['apparatus']){echo "SELECTED";} ?> ><?php echo substr($apparatus['apparatus'], 5); ?></option>
<?php endforeach;?>
You have it right in your question, but not in your code
<?php
foreach ($apparatuslist as $apparatus):?>
<option value="<?php echo $apparatus['apparatus'];?>" <?php if ($driveron['apparatus'] == $apparatus['apparatus']){echo "selected=\"selected\"";} ?> ><?php echo substr($apparatus['apparatus'], 5); ?></option>
<?php endforeach;?>
Should do the trick..
The code is correct. It's optional whether you write select="selected" or jus "selected" that doesn't effect firefox.The code is correct but not working means the problem in browser i guess. Either it is cache problem as newer version of firefox has cache problem or there may be other kind of problem in firefox. Please check in other computer's firefox.
correct syntax is: selected="selected" in OPTION tag

how to keep the choosed data in the <select> element? HTML

here I have stupid question, hope you can help me.
I create a menu using Select element and option like this:
<option selected="selected">Select type...</option>
<option value="1">Doctor</option>
<option value="2">Patient</option>
and every time I need to pick one value from this menu and use the submit button next to it to transfer data.
But every time the page refreshed, this menu will reveal: Select type...
I want it to reveal the value I chose last time, but don't know how.
Many thanks in advance!!
You'll want to move that selected="selected" onto the selected option.
Doing so in PHP isn't too rough. Just check the $_POST or $_GET (however you sent the form) value for your select box, such as $_POST["selectBox"] for each value down the list. When you find a match, echo out the selected="selected" string there. If the value was empty, output it on your default value.
The easiest way to achieve this is to populate the <select> options in an array, then loop through it to display the <option> list and mark them as selected is the $_POST variable matches the correct value:
<?php $myselect = array(1=>'Doctor', 2=>'Patient'); ?>
<select name="myselect">
<option>Select type...</option>
<?php foreach ($myselect as $value => $label): ?>
<option value="<?php echo $value; ?>"<?php if (isset($_POST['myselect']) && $_POST['myselect'] == $value) echo ' selected'; ?>>
<?php echo $label; ?>
</option>
<?php endforeach; ?>
</select>
<select name="myselect">
<?php
$myselect = array('Select type...','Doctor','Patient');
for($i=0; $i<=2; $i++){
echo "<option value=\"{myselect[$i]}\"";
if (isset($_POST['myselect']) && $_POST['myselect'] == $myselect[$i]){
echo 'selected=\"selected\"';
}
echo ">{$myselect[$i]}</option>";
}
?>
</select>
You have to use the server-side language of you choice to store the selected value in a database, xml or text file.
Edit : I think I may have misunderstood your question.
There are a few ways to do this.
On submit you can save that value as a $_SESSION value and use that to set the select on page load.
Using Javascript you can either set a cookie on change or alter the url to add a parameter (url?selecttype=1) and set that on page load using PHP.
There's a good use of cookies in JS on quirksmode: http://www.quirksmode.org/js/cookies.html
You need to change which one is selected to match the request....
function create_select($properties, $opts)
{
$out="<select ";
foreach ($properties as $propname=>$propval) {
$out.=" $propname='$propval'";
}
$out.=">\n";
foreach ($opts as $val=>$caption) {
$out.="<option value='$value'";
if ($_REQUEST[$properties['name']]==$val) $out.=" SELECTED";
$out.=">$caption</option>\n";
}
$out.="</select>";
return $out;
}
print create_select(array('name'=>'direction',
'id'=>'direction',
'class'=>'colourful',
'onChange'=>''),
array('N'=>'North',
'S'=>'South',
'E'=>'East',
'W'=>'West'));

Categories