Choose correct Select option from MySQL Database - php

I have this HTML/PHP Code that lists options in a select element.
Whats the best way to make the correct option selected based on a record from a MySQL database:
This works fine, but is there any easier way to do it with one line of code rather than doing an if statement per option?
<select name="status" id="status">
<option value="Open"<?php if($ticket["status"]=="Open"){echo('selected="selected"');}?>>Open</option>
<option value="Needs Action"<?php if($ticket["status"]=="Needs Action"){echo('selected="selected"');}?>>Needs Action</option>
<option value="Customer Reply"<?php if($ticket["status"]=="Customer Reply"){echo('selected="selected"');}?>>Customer Reply</option>
<option value="Completed"<?php if($ticket["status"]=="Completed"){echo('selected="selected"');}?>>Completed</option>
</select>

use an array:
echo "<select name='status' id='status'>";
$statuses = array('Open', 'Needs Action', 'Customer Reply', 'Completed');
foreach ($statuses as $status) {
echo "<option value='$status' " . ($ticket['status'] == $status) ? "selected='selected'" : "" . "/>";
}
echo "</select>";

You may want to put those values in the database or if you want to avoit it, just put them into an array and print all the options using a loop and mark as selected the right one.

Yes, the code can be shorter (and much more readable):
if($ticket["status"]=="Open") {
$openSelected = "selected='selected'";
}
if($ticket["status"]=="Needs Action") {
$needsActionSelected = "selected='selected'";
}
if($ticket["status"]=="Customer Reply") {
$customerReplySelected = "selected='selected'";
}
if($ticket["status"]=="Completed") {
$completedSelected = "selected='selected'";
}
<select name="status" id="status">
<option value="Open" <?php print($openSelected) ?>>Open</option>
<option value="Needs Action"<?php print($needsActionSelected) ?>>Needs Action</option>
<option value="Customer Reply"<?php print($customerReplySelected) ?>>Customer Reply</option>
<option value="Completed"<?php print($completedSelected) ?>>Completed</option>
</select>
EDIT// #Barmar has a better answer.

Related

How to get certain data from database based on primary key from select option? [duplicate]

Is there any way to set the selected item in a drop down box using the following 'type' code?
<select selected="<?php print($row[month]); ?>"><option value="Janurary">January</option><option value="February">February</option><option value="March">March</option><option value="April">April</option></select>
The database holds a month.. and I want to allow on the edit page, them to choose this month.. but it to be pre-filled with their current setting?
You need to set the selected attribute of the correct option tag:
<option value="January" selected="selected">January</option>
Your PHP would look something like this:
<option value="January"<?=$row['month'] == 'January' ? ' selected="selected"' : '';?>>January</option>
I usually find it neater to create an array of values and loop through that to create a dropdown.
You mark the selected item on the <option> tag, not the <select> tag.
So your code should read something like this:
<select>
<option value="January"<?php if ($row[month] == 'January') echo ' selected="selected"'; ?>>January</option>
<option value="February"<?php if ($row[month] == 'February') echo ' selected="selected"'; ?>>February</option>
...
...
<option value="December"<?php if ($row[month] == 'December') echo ' selected="selected"'; ?>>December</option>
</select>
You can make this less repetitive by putting all the month names in an array and using a basic foreach over them.
You can use this method if you use a MySQL database:
include('sql_connect.php');
$result = mysql_query("SELECT * FROM users WHERE `id`!='".$user_id."'");
while ($row = mysql_fetch_array($result))
{
if ($_GET['to'] == $row['id'])
{
$selected = 'selected="selected"';
}
else
{
$selected = '';
}
echo('<option value="'.$row['id'].' '.$selected.'">'.$row['username'].' ('.$row['fname'].' '.substr($row['lname'],0,1).'.)</option>');
}
mysql_close($con);
It will compare if the user in $_GET['to'] is the same as $row['id'] in table, if yes, the $selected will be created. This was for a private messaging system...
Simple and easy to understand example by using ternary operators to set selected value in php
<?php $plan = array('1' => 'Green','2'=>'Red' ); ?>
<select class="form-control" title="Choose Plan">
<?php foreach ($plan as $id=> $value) { ?>
<option value="<?php echo $id;?>" <?php echo ($id== '2') ? ' selected="selected"' : '';?>><?php echo $value;?></option>
<?php } ?>
</select>
Its too old but I have to add my way as well :) because it is generic and useful especially when you are using static dropdown values.
function selectdCheck($value1,$value2)
{
if ($value1 == $value2)
{
echo 'selected="selected"';
} else
{
echo '';
}
return;
}
and in you dropdown options you can use this function like this and you can use this as many as you can because it fits with all of your select boxes/dropdowns
<option <?php selectdCheck($row[month],january); ?> value="january">january</option>
:) I hope this function help others
Simple way
<select class ="dropdownstyle" name="category" selected="<?php print($messageeditdetails[0]['category_id']); ?>">
<option value=""><?php echo "Select"; ?></option>
<?php foreach ($dropdowndetails as $dropdowndetails) { ?>
<option <?php if($messageeditdetails[0]['category_id'] == $dropdowndetails['id']) { ?> selected="<?php echo $dropdowndetails['id']; ?>" <?php } ?> value="<?php echo $dropdowndetails['id']; ?>"><?php echo $dropdowndetails['category_name']; ?></option>
<?php } ?>
</select>
This is the solution that I came up with...
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="select_month">
<?php
if (isset($_POST['select_month'])) {
if($_POST["select_month"] == "January"){
echo '<option value="January" selected="selected">January</option><option value="February">February</option>';
}
elseif($_POST["select_month"] == "February"){
echo '<option value="January">January</option><option value="February" selected="selected">February</option>';
}
}
else{
echo '<option value="January">January</option><option value="February">February</option>';
}
?>
</select>
<input name="submit_button" type="submit" value="Search Month">
</form>
A Simple Solution:
It work's for me
<div class="form-group">
<label for="mcategory">Select Category</label>
<select class="form-control" id="mcategory" name="mcategory" required>
<option value="">Please select category</option>
<?php foreach ($result_cat as $result): ?>
<option value="<?php echo $result['name'];?>"<?php
if($result['name']==$mcategory){
echo 'selected';
} ?>><?php echo $result['name']; ?></option>
}
<?php endforeach; ?>
</select>
</div>
Check this:
<select class="form-control" id="department" name="department" type="text">
<option value="medical-furniture" #if($list->department == "medical-furniture") selected #endif>Medical furniture</option>
<option value="medical-table" #if($list->department == "medical-table") selected #endif>Medical table</option>
<option value="service" #if($list->department == "service") selected #endif>Service</option>
</select>
My suggestion is to leverage the hidden/collapse attribute. Try with this example:
<select>
<option value="echo $row[month]" selected disabled hidden><? echo $row[month] ?></option>
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
</select>
in case of null for $row[month] the selected item is blank and with data, it would contain less codes for many options and always working for HTML5 and bootstrap etc...
If you have a big drop down. it's much easier to use jQuery with PHP.
This is how to do it:
<script>
$(document).ready(function () {
$('select[name="country"]').val('<?=$data[0]['Country']?>');
});
</script>
The easiest solution for the selected option in dropdown using PHP is following
<select class="form-control" name="currency_selling" required >
<option value="">Select Currency</option>
<option value="pkr" <?=$selected_currency == 'pkr' ? ' selected="selected"' : '';?> >PKR</option>
<option value="dollar" <?=$selected_currency == 'dollar' ? ' selected="selected"' : '';?> >USD</option>
<option value="pounds" <?=$selected_currency == 'pounds' ? ' selected="selected"' : '';?> >POUNDS</option>
<option value="dirham" <?=$selected_currency == 'dirham' ? ' selected="selected"' : '';?> >DRHM</option>
</select>
You can try this after select tag:
<option value="yes" selected>yes</option>
<option value="no">no</option>

Whats the best way to show selected options on a form when reloaded using PHP

I would like the select option the user selected to be shown when the form is reloaded. I am currently using bootstrap select picker to style the drop down. Right now I am creating an array and echoing out a selected class based on the value stored in the database.
This is not a major problem with a small amount of options like the code provided below, however with a select box with larger amounts of options this obviously amounts to lots of extra code.
There must be a smarter way to do this than the code i'm using below. Can anyone help?
<select class="selectpicker" name="Do_You_Have_A_Job_Spec_You_Can_Email">
<option value="" <?php if ($user_data_array['Do_You_Have_A_Job_Spec_You_Can_Email'] == '') echo "selected='selected'"; ?>>Please Select</option>
<option value="Yes" <?php if ($user_data_array['Do_You_Have_A_Job_Spec_You_Can_Email'] == 'Yes') echo "selected='selected'"; ?>>Yes</option>
<option value="No" <?php if ($user_data_array['Do_You_Have_A_Job_Spec_You_Can_Email'] == 'No') echo "selected='selected'"; ?>>No</option>
</select>
If the option's are static you could use ternary operators, so it will be something like :
<?php $selected_option = $user_data_array['Do_You_Have_A_Job_Spec_You_Can_Email']; ?>
<select class="selectpicker" name="Do_You_Have_A_Job_Spec_You_Can_Email">
<option value="" <?php echo $selected_option==''?'selected':''; ?>>Please Select</option>
<option value="Yes" <?php echo $selected_option=='Yes'?'selected':''; ?>>Yes</option>
<option value="No" <?php echo $selected_option=='No'?'selected':''; ?>>No</option>
</select>
Hope this helps.
<?php
$text = $user_data_array['Do_You_Have_A_Job_Spec_You_Can_Email'];
?>
<select class="selectpicker" name="Do_You_Have_A_Job_Spec_You_Can_Email">
<option value="">Please Select</option>
<option value="Yes" <?php echo $text == 'Yes' ? 'selected' : ''; ?>> Yes </option>
<option value="No" <?php echo $text == 'No' ? 'selected' : ''; ?>> No </option>
</select>
Alternative Way
"..however with a select box with larger amounts of options this
obviously amounts to lots of extra code.".
In this case, when you are having lots of data for dropdown. You can create a table where you can have both option name and option value.
job_specification_table
id option_value option_name
1 Please Select
2 Yes Yes
3 No No
.
.
.
Then, retreive those values and check for user_data and according to it, option will get selected.
<?php
$sql = "SELECT * FROM job_specification_table";
$result = mysqli_query($db_con,$sql);
$text = $user_data_array['Do_You_Have_A_Job_Spec_You_Can_Email'];
?>
<select class="selectpicker" name="Do_You_Have_A_Job_Spec_You_Can_Email">
<?php
while ($row = mysqli_fetch_array($result)){
$option_value = $row['option_value'];
$selected = ($option_value == $text) ? "selected" : "";
?>
<option value="<?=$option_value;?>" <?=$selected;?>>
<?=$row['option_name'];?>
</option>
<?php }?>
</select>
Here is more readable solution:
<select class="selectpicker" name="Do_You_Have_A_Job_Spec_You_Can_Email">
<option value=
<?php
$choise = $user_data_array['Do_You_Have_A_Job_Spec_You_Can_Email'];
switch ($choise) {
case 'Yes':
echo '"Yes" selected="selected" >Yes';
break;
case 'No':
echo '"No" selected="selected" >No';
break;
case '':
echo '"" selected="selected" >Please Select';
break;
}
?>
</option>
</select>

Displaying selected option from database in a select option tag

This is a simple one, i know it is i just cant think of a good logical way to do this.
I have the following code:
<select name="Title[]" class="form-control">
<option value="">Select title...</option>
<option value="Mr">Mr</option>
<option value="Miss">Miss</option>
<option value="Mrs">Mrs</option>
<option value="Ms">Ms</option>
<option value="Prof">Prof</option>
<option value="Doctor">Doctor</option>
</select>
What i want to do is on my edit client page, have their previously selected option displayed. So for example, if Doctor was selected at sign up, it would be selected by default on the edit page. I know i could do this like:
<option value="Doctor" <?php if($client_title == 'Doctor'){ echo 'selected'; } ?>>Doctor</option>
But it seems like a bit of a redundant way to do it. Can this be done easily with a do while statement?
Sorry for the simple request, having a bit of a slow day today! haha
<select name="title[]" class="form-control">
<?php
$titles = array('Mr', 'Miss', 'Mrs', 'Ms', 'Prof', 'Doctor');
foreach ($titles as $title) {
$selected = $client_title == $title ? ' selected="selected"' : null;
?>
<option value="<?php echo $title; ?>"<?php echo $selected; ?>><?php echo $title; ?></option>
<?php
}
?>
</select>

How to set selected value in drop list in HTML?

How to set selected value in drop list in HTML in Edit Form?
The selected value came from MySql
This code is not work !! >> selected=""
<select name="TutorGender" id="TutorGender" selected="<?php echo $Gender ?>">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
W3Schools does a good job of explaining this here
http://www.w3schools.com/tags/att_option_selected.asp
Your code might look something like this.
<select name="TutorGender" id="TutorGender">
<option value="Male" <?php if($Gender == "Male") echo "selected"; ?>>Male</option>
<option value="Female" <?php if($Gender == "Female") echo "selected"; ?>>Female</option>
</select>
Though my PHP syntax may be a little off, but you should get the idea.
Selected goes on the option tag, not on the select tag.
<select name="TutorGender" id="TutorGender" >
<option value="Male" selected="selected">Male</option>
<option value="Female">Female</option>
</select>
<select name="TutorGender" id="TutorGender">
<option value="Male" <?php if($Gender=='Male') echo 'selected' ?>>Male</option>
<option value="Female" <?php if($Gender=='Female') echo 'selected' ?>>Female</option>
</select>
The selected attribute appears on the option(s) that should be selected, not the select element (if it went on the select element itself, then (since multiple options can be selected at the same time) it would have to take a list of ids and you would need to add an id to each option).
<option value="foo" selected>Foo</option>
Generally you would have an array of values (or of value/human text pairs) that you would loop over. (i.e. you wouldn't hard code your options)
You would generate one option each time you went around the loop, and test to see if you should include a selected attribute each time.
<option <?php if($Gender == 'Male'){ echo(' selected '); } ?> value="Male">Male</option>
<option <?php if($Gender == 'Female'){ echo(' selected '); } ?> value="Female">Female</option>
<select name="TutorGender" id="TutorGender">
<?php
$genders = array( 'Male', 'Female' );
foreach( $genders as $value )
{
$selected = ( $Gender == $value )? ' selected="selected"': '';
echo '<option value="' . $value . '"' . $selected . '>' . $value . '</option>';
}
?>
</select>
just another way of doing it. I prefer to use shorthand if statements for code such as this.
<select name="TutorGender" id=\"TutorGender\">
<option value="Male" <?php echo ($Gender == "Male" ? "selected" : ""); ?>>Male</option>
<option value="Female" <?php echo ($Gender == "Female" ? "selected" : ""); ?>>Female</option>
here is a link to using shorthand "if" statements.
In a case where I needed to use a select as part of a user update form that was populated via a database I found the array option works best. The line by line option can get very unwieldy very quickly. This way you simply need to add an option to the $optionDept array should any new options be required. In this example "$row['Dept']" is from the larger overarching results from the database request.
$optionDept= array('sales','warehouse','inspection','production','accounts','admin','inactive');
$optionCount= count($optionDept);
echo"<select name=\"UserDept\">";
for($x = 0; $x < $optionCount; $x++) {
echo"<option value=".$optionDept[$x];
if($optionDept[$x]==$row['Dept']){echo " selected";}
echo">".$optionDept[$x]."</option>";}
echo"</select</P>
try this
if you want to keep male as selected
<select name="TutorGender" id="TutorGender" >
<option value="Male" selected="selected">Male</option>
<option value="Female">Female</option>
</select>
This worked for me: I send througt the GET method of the submit the value i want to restore, and then in the php, AT THE END OF THE PAGE (if not, default values will be set if the code is before the php) i set those values.
echo "select_language.selectedIndex = ".$_GET['iL'].";";

<select> dropdown default value

I have this code:
if(isset($_POST['search']))
{
$res1=mysql_query("SELECT * FROM aircraft where acode = '$_POST[ac]'") or die(mysql_error());
while($row=mysql_fetch_array($res1))
{
$airc=$row['acode'];
$amode=$row['amodel'];
$stat=$row['status'];
$rem=$row['remarks'];
echo "<center><table><form name=\"frmMain\" method=\"post\">
<tr><td><font face=consolas><b>Aircraft Code:</b></font></td><td><input type=text name=arc value='$airc' readonly=readonly></td></tr>
<tr><td><font face=consolas><b>Aircraft Model:*</b></font></td><td><input type=text name=am value='$amode'></td></tr>
<tr><td><font face=consolas><b>Status:*</b></font></td><td><input type=text name=st value='$stat'></td></tr>
<tr><td><font face=consolas><b>Remarks:*</b></font></td><td><input type=text name=rm value='$rem'></td></tr></table>";
}
}
On submit 'search' button, this code displays the data from aircraft table. The user is allowed to update the data with the (*) sign.
Since the Status are the following by default (Available, Not Available), I changed this
<tr><td><font face=consolas><b>Status:*</b></font></td><td><input type=text name=st value='$stat'></td></tr>
to this,
<tr><td><font face=consolas><b>Status:*</b></font></td><td><select name=st>
<option value=Available>Available</option>
<option value='Not Available'>Not Available</option>
</select></td></tr>
But I want the dropdown to have it's default value depending on
$stat=$row['status']; since this is an update form.
If the data being retrieved has it's status 'Available', then the dropdown should have it's default value as 'Available'.
How can I achieve that? I tried <select name=status value='$stat'> but it doesn't work. Any help will be appreciated. Thanks!
Just put selected="selected" on the option depending on your $row['status'],
<option selected="selected" value="available">Available</option>
write Available and Unavailable into an array
$theArray = array("Available","Not Available");
loop the array:
<tr><td><font face=consolas><b>Status:*</b></font></td><td><select name=st>
<?php
foreach ($theArray as $key => $value) {
if ($value == $stat) {
echo('<option selected="selected" value='.$value.'>'.$value.'</option>');
} else {
echo('<option value='.$value.'>'.$value.'</option>');
}
}
?>
</select></td></tr>
and in each loop we check if the value in the array, is the same as it is in the variable, if so, we put the selected there
understand the logic?
<select name=status>
<option value="available" <?php if($row['status']=="available") echo "selected=\"selected\""; ?>>Available</option>
<option value="unavailable" <?php if($row['status']=="unavailable") echo "selected=\"selected\""; ?>>Unvailable</option>
</select>
Basically echo selected="selected" for the option depending on value of the concerned field.
<?php
$status = "navail";
?>
<select name="sel">
<option value="avail" <?php if($status == "avail") echo "SELECTED";?> > Avail </option>
<option value="navail" <?php if($status == "navail") echo "SELECTED";?> > Navail </option>
</select>
You can define your variable value with additional option tag and mark that as selected like:
<select name="role" id="role">
<!-- This is default define value using php variable $r -->
<option selected="selected" value="<?php echo $r; ?>" disabled="disabled"><?php echo $r; ?></option>
<!-- Other options values -->
<option value="2">Option-2</option>
<option value="2">Option-2</option>
</select>
You can set the selected dropdown option from database as below:
<select name="status">
<option <?php echo ($row['status'] == 'Available') ? 'selected' : '' ?> value='Available'>Available</option>
<option <?php echo ($row['status'] == 'Not Available') ? 'selected' : '' ?> value='Not Available'>Not Available</option>
</select>
Declare the options in an array like
$arr = array("available" => "available","unavailable" => "unavailable");
and input the drop down like this
echo form_dropdown("st", $arr, set_value("st", (isset($row['status'];) ? $row['status']; : ""))
This is the method commonly used in frameworks like codeigniter.. i think it works in core php too..
its my first time here though and i tried using basic principles in php, dont know if this helps you but if you're trying to grab the defaulted value which you inputted on your database then edit it again i suggest you try this one
<select name="st">
<?php if($row['status']=="Available"){?><option value="Available">Available</option><?php }?>
<?php if($row['status']=="Unavailable"){?><option value="Unavailable">Unavailable</option><?php }?>
</select>
Assuming that the column name in your database is 'status', give it a try works for me

Categories