PHP/HTML Showing selected option in dropdown from sql query - php

I wasn't sure how to title my question, I'm basically asking if anyone knows a better way to approach this. I'm using this function below to show which option is pulled from the DB, I'm wondering if there is a more compact way or better way to do this other than elseif each ID
function access_option($access)
{
if ($access == 0)
{
echo '<option value="0" selected>Member</option>
<option value="1">Streamer</option>
<option value="2">Moderator</option>
<option value="3">Manager</option>
<option value="4">Administrator</option>
<option value="5">Senior Administrator</option>';
}
elseif ($access == 1)
{
echo '<option value="0">Member</option>
<option value="1" selected>Streamer</option>
<option value="2">Moderator</option>
<option value="3">Manager</option>
<option value="4">Administrator</option>
<option value="5">Senior Administrator</option>';
}
elseif ($access == 2)
{
echo '<option value="0">Member</option>
<option value="1">Streamer</option>
<option value="2" selected>Moderator</option>
<option value="3">Manager</option>
<option value="4">Administrator</option>
<option value="5">Senior Administrator</option>';
}
elseif ($access == 3)
{
echo '<option value="0">Member</option>
<option value="1">Streamer</option>
<option value="2">Moderator</option>
<option value="3" selected>Manager</option>
<option value="4">Administrator</option>
<option value="5">Senior Administrator</option>';
}
elseif ($access == 4)
{
echo '<option value="0">Member</option>
<option value="1">Streamer</option>
<option value="2">Moderator</option>
<option value="3">Manager</option>
<option value="4" selected>Administrator</option>
<option value="5">Senior Administrator</option>';
}
elseif ($access == 5)
{
echo '<option value="0">Member</option>
<option value="1">Streamer</option>
<option value="2">Moderator</option>
<option value="3">Manager</option>
<option value="4">Administrator</option>
<option value="5" selected>Senior Administrator</option>';
}
}
Is this the best way to do it?

You can do it with less repetition using ternary operators:
function access_option($access)
{
echo '<option value="0"'.($access == 0 ? ' selected' : '').'>Member</option>';
echo '<option value="1"'.($access == 1 ? ' selected' : '').'>Streamer</option>';
echo '<option value="2"'.($access == 2 ? ' selected' : '').'>Moderator</option>';
echo '<option value="3"'.($access == 3 ? ' selected' : '').'>Manager</option>';
echo '<option value="4"'.($access == 4 ? ' selected' : '').'>Administrator</option>';
echo '<option value="5"'.($access == 5 ? ' selected' : '').'>Senior Administrator</option>';
}

You can loop over the values, which are held in an array, and set the selected value dynamically. This method makes it easy to add/remove options in the future by adjusting the array -
function access_option($access)
{
$options = ["Member", "Streamer", "Moderator", "Manager", "Administrator", "Senior Administrator"];
foreach($options as $key=>$value)
{
echo '<option value="'.$key.'"'.($key==$access ? ' selected' : '').'>'.$value.'</option>';
}
}

Ternary operators will reduce the size of it as mentioned as another answer. You can also use the switch statement. Similar to if and elseif but easier and will reduce your code.
Example:
<?php
function access_option($access)
{
switch ($access) {
case 0: echo "access equals 0";
case 1: echo "access equals 1";
case 2: echo "access equals 2";
}
}
?>

Related

How to echo php and html of dropdown list?

I have problem with my codes and I'm still new to php. Please help me :)
echo "<td><select>
<option value='1'<?php if($row['Staf_Kamp'] == '1') { ?> selected='selected'<?php } ?>>1</option>;
<option value='2'<?php if($row['Staf_Kamp'] == '2') { ?> selected='selected'<?php } ?>>2</option>;
<option value='3'<?php if($row['Staf_Kamp'] == '3') { ?> selected='selected'<?php } ?>>3</option>;
</select></td>";
I am expecting the dropdown list that I have selected before edit will be selected in the edit page. But it is not working.
When echoing, you are already in a php context, so there is no need to use <?php ?> tags again. You can just concatenate the variables in your string.
echo "<td><select>
<option value='1'" . ($row['Staf_Kamp'] == '1' ? ' selected="selected"' : '') . ">1</option>;
<option value='2'" . ($row['Staf_Kamp'] == '2' ? ' selected="selected"' : '') . ">2</option>;
<option value='3'" . ($row['Staf_Kamp'] == '3' ? ' selected="selected"' : '') . ">3</option>;
</select></td>";
Try this:
<td><select>
<option value='1'<?php if($row['Staf_Kamp'] == '1') { echo ' selected'; } ?>>1</option>
<option value='2'<?php if($row['Staf_Kamp'] == '2') { echo ' selected'; } ?>>2</option>
<option value='3'<?php if($row['Staf_Kamp'] == '3') { echo ' selected'; } ?>>3</option>
</select></td>
You only need ; when working inside the <?php ?> tags so strip those out. Also save the opening and closing by just echoing out the selected value. Also the correct syntax is selected and not selected='selected'
you can not echo a string and put php code into the string
correct code:
<td>
<select>
<option value='1'<?php if($row['Staf_Kamp'] == '1') { ?> selected='selected'<?php } ?>>1</option>
<option value='2'<?php if($row['Staf_Kamp'] == '2') { ?> selected='selected'<?php } ?>>2</option>
<option value='3'<?php if($row['Staf_Kamp'] == '3') { ?> selected='selected'<?php } ?>>3</option>
</select>
</td>

Echo 'selected' in html5 dropdown form using PHP

I have a form that fetches user info into the $row variable so forms are populated if the row exists if the database, but then saves any new input through the $_POST global variable, in case the user makes a mistake elsewhere on the form. It all works great.
<label for="qualification2">Grade:</label>
<input type="text" name="qualification2" id="grade2" class="form-control"
value="<?php if(isset($_POST['qualification2'])) {
echo $_POST['qualification2'];
} else { echo ($row ['qualification2']); } ?>">
I would like to do similar using a selection dropdown box but the code doesn't seem to work the same with dropdown boxes and I wonder what I'm doing wrong or if this is even possible.
I've also tried echo from the $row variable but that doesn't work either
<?php if($row['qualMonth2'] == 'February') { echo ' selected'; } ?>
This is my code:
<select input type="text" name="qualMonth2" id="qualMonth2" value="Select Month">
<option value="January" <?php if(isset($_POST['qualMonth2']) == 'January') { echo ' selected'; } ?>>January</option>
<option value="February" <?php if(isset($_POST['qualMonth2']) == 'February') { echo ' selected'; } ?>>February</option>
<option value="March" <?php if(isset($_POST['qualMonth2']) == 'March') { echo ' selected'; } ?>>March</option>
<option value="April" <?php if(isset($_POST['qualMonth2']) == 'April') { echo ' selected'; } ?>>April</option>
<option value="May" <?php if(isset($_POST['qualMonth2']) == 'May') { echo ' selected'; } ?>>May</option>
<option value="June" <?php if(isset($_POST['qualMonth2']) == 'June') { echo ' selected'; } ?>>June</option>
<option value="July" <?php if(isset($_POST['qualMonth2']) == 'July') { echo ' selected'; } ?>>July</option>
<option value="August" <?php if(isset($_POST['qualMonth2']) == 'August') { echo ' selected'; } ?>>August</option>
<option value="September" <?php if(isset($_POST['qualMonth2']) == 'September') { echo ' selected'; } ?>>September</option>
<option value="October" <?php if(isset($_POST['qualMonth2']) == 'October') { echo ' selected'; } ?>>October</option>
<option value="November" <?php if(isset($_POST['qualMonth2']) == 'November') { echo ' selected'; } ?>>November</option>
<option value="December" <?php if(isset($_POST['qualMonth2']) == 'December') { echo ' selected'; } ?>>December</option>
</select>
isset validates to true or false based on if variable is set or not. You can't check the value just with isset.
Use a small utility function to check condition:
function checkSelected($value) {
if(isset($_POST['qualMonth2']) && $_POST['qualMonth2'] == $value) {
return true;
} else {
return false;
}
}
Your select element should be then:
<select input type="text" name="qualMonth2" id="qualMonth2" value="Select Month">
<option value="January" <?php echo checkSelected('January') ? 'selected':'' ?>>January</option>
<option value="February" <?php echo checkSelected('February') ? 'selected':'' ?>>February</option>
<option value="March" <?php echo checkSelected('March') ? 'selected':'' ?>>March</option>
<option value="April" <?php echo checkSelected('April') ? 'selected':'' ?>>April</option>
<option value="May" <?php echo checkSelected('May') ? 'selected':'' ?>>May</option>
<option value="June" <?php echo checkSelected('June') ? 'selected':'' ?>>June</option>
<option value="July" <?php echo checkSelected('July') ? 'selected':'' ?>>July</option>
<option value="August" <?php echo checkSelected('August') ? 'selected':'' ?>>August</option>
<option value="September" <?php echo checkSelected('September') ? 'selected':'' ?>>September</option>
<option value="October" <?php echo checkSelected('October') ? 'selected':'' ?>>October</option>
<option value="November" <?php echo checkSelected('November') ? 'selected':'' ?>>November</option>
<option value="December" <?php echo checkSelected('December') ? 'selected':'' ?>>December</option>
</select>
Lets look at what you wrote..
<option value="February" <?php if(isset($_POST['qualMonth2']) == 'February') { echo ' selected'; } ?>>February</option>
What you're saying is.. If there is a value set for qualMonth2 (true / false), compare that against a string..
So you're comparing true || false against a string.
isset($_POST['qualMonth2']) returns true // false.
So none will ever be selected.
Refactor it..
<?php
$month = "";
if(isset($_POST['qualification2'])){
$month = $_POST['qualification2'];
}
?>
Then use $month as the comparative value.
<option value="July" <?php if($month == 'July') { echo ' selected'; } ?>>July</option>
I prefer to perform these checks in Javascript (I prefer JQuery), I think it cleans up the code, but you could also simplify this greatly by using a loop with generated months.
Loop through 1-12 for output
<select input type="text" name="qualMonth2" id="qualMonth2" value="Select Month">
<?php
for($i=1; $i<=12; $i++) {
$dateObj = DateTime::createFromFormat('!m', $i);
$monthName = $dateObj->format('F');
echo "<value>" . $monthName . "</option>";
}
?>
</select>
This approach takes a DRY (Do not repeat) approach. If you need to modify something, you only need to modify 1 line of code versus 12.
Jquery for choosing value (defaults to January if $_POST['qualMonth2'] is not set):
<script>
$('#qualMonth2').val("<?php echo (isset($_POST['qualMonth2'])) ? $_POST['qualMonth2'] : 'January' ?>");
</script>
Take what you will from this answer, I just showed you two possibilities, you can certainly avoid Javascript by adding a check in the loop if you want.

Limit of number of checks in a PHP If statement

I'm new to PHP and HTML I have several other IF statements with two or three OR in it and they seem to work just fine.
What I'm checking for is 'NULL', 'blank', 'space' or text 'None'. If I find any of these I want to do the select statement. If no matches I would like to use the $AT_Med_1_1 data which has been pull out of a database.
IF statement as shown below which does not see me to work. It always drops into the SELECT statement even when $AT_Med_1_1 is something else.
if ($AT_Med_1_1 == '' or $AT_Med_1_1 == NULL or $AT_Med_1_1 == ' ' or $AT_Med_1_1 = 'None') {
<select name="AT_Med_1_2">
<option value="None">None</option>
<option value="Oral_Zofran">Oral Zofran</option>
<option value="IV_Zofran">IV_Zofran</option>
<option value="Oxygen">Oxygen</option>
<option value="Ibuprofen">Ibuprofen</option>
<option value="Aetaminothen">Aetaminothen</option>
<option value="Upinephrne">Upinephrne</option>
<option value="Xopenex">Xopenex</option>
<option value="Albuterol">Albuterol</option>
<option value="Valium">Valium</option>
<option value="Magnesiunsulphate">Magnesiunsulphate</option>
<option value="Diphenhyamine">Diphenhyamine</option>
<option value="Ketorolac">Ketorolac</option>
<option value="Promethazion">Promethazion</option>
<option value="Oral_Fluids_Soup">Oral Fluids Soup</option>
<option value="Oral_Fluids_Electrolyte">Oral Fluids Electrolyte</option>
<option value="Oral_Fluids_Water">Oral Fluids Water</option>
</select>
<?php
} else {
// echo 'Showing $AT_';
echo $AT_Med_1_2;
echo nl2br("\n");
}
?>
If I change the IF statement to several elseif it seem to work correctly
if ($AT_Med_1_1 == '')
{
goto test1;
} else if ($AT_Med_1_1 == NULL)
{
goto test1;
} else if ($AT_Med_1_1 == ' ')
{
goto test1;
} else if ($AT_Med_1_1 == 'None')
{
goto test1;
}
goto test;
test1:
?>
<select name="AT_Med_1_1">
<option value="None">None</option>
<option value="Oral_Zofran">Oral Zofran</option>
<option value="IV_Zofran">IV_Zofran</option>
<option value="Oxygen">Oxygen</option>
<option value="Ibuprofen">Ibuprofen</option>
<option value="Aetaminothen">Aetaminothen</option>
<option value="Upinephrne">Upinephrne</option>
<option value="Xopenex">Xopenex</option>
<option value="Albuterol">Albuterol</option>
<option value="Valium">Valium</option>
<option value="Magnesiunsulphate">Magnesiunsulphate</option>
<option value="Diphenhyamine">Diphenhyamine</option>
<option value="Ketorolac">Ketorolac</option>
<option value="Promethazion">Promethazion</option>
<option value="Oral_Fluids_Soup">Oral Fluids Soup</option>
<option value="Oral_Fluids_Electrolyte">Oral Fluids Electrolyte</option>
<option value="Oral_Fluids_Water">Oral Fluids Water</option>
</select>
<?php
goto endtest;
test:
echo $AT_Med_1_1;
echo nl2br("\n");
endtest:
if (... or $AT_Med_1_1 = 'None') {
For the last condition you accidentally wrote = instead of ==.

A better solution to handle PHP and HTML <option> logic

Wondering if you can show me a better way to handle this logic? I wrote this and am very ashamed of it. Can you show me a better optimized version of this logic?
P.S $result["item"]; returns an integer.
$type = $result["item"];
switch ($type){
case "1":
$type_output = '
<option value="1" selected>Cash</option>
<option value="2">Cheque</option>
<option value="3">Debit Card</option>
<option value="4">Credit Card</option>';
break;
case "2":
$type_output = '
<option value="1">Cash</option>
<option value="2" selected>Cheque</option>
<option value="3">Debit Card</option>
<option value="4">Credit Card</option>';
break;
case "3":
$type_output = '
<option value="1">Cash</option>
<option value="2">Cheque</option>
<option value="3" selected>Debit Card</option>
<option value="4">Credit Card</option>';
break;
case "4":
$type_output = '
<option value="1">Cash</option>
<option value="2">Cheque</option>
<option value="3">Debit Card</option>
<option value="4" selected>Credit Card</option>';
break;
}
html
<td>
<select style="width:200px;" name="payment_type">
<option value=""> </option>
'.$type_output.'
</select>
</td>
Thank you
I would use this approach
$type = $result["item"];
$type_output = "";
$options =array(
"1"=>"cash",
"2"=>"Cheque",
"3"=>"Debit Card",
"4"=>"Credit Card",
);
foreach($options as $value=>$text) {
$type_output .= "<option value=\"$value\"".($type==$value? " selected" : "").">$text</option>\n";
}
you could do it this way and only once
<option value="1" <?php if ($type == 1) echo "selected"; ?>>Cash</option>
<option value="2" <?php if ($type == 2) echo "selected"; ?>>Cheque</option>
<option value="3" <?php if ($type == 3) echo "selected"; ?>>Debit Card</option>
<option value="4" <?php if ($type == 4) echo "selected"; ?>>Credit Card</option>
You're repeating a lot of stuff here. You can do something like
<option value="..." <?php if($type == 1) { print "selected"; } ?> >Something</option>
This would work, however you're probably better off using a template engine and letting it handle this sort of stuff for you.
http://www.smarty.net/docsv2/en/language.function.html.options.tpl
Try this
type_output = '
<option value="1"'.($type == 1 ? " selected" : "").'>Cash</option>
<option value="2"'.($type == 2 ? " selected" : "").'>Cheque</option>
<option value="3"'.($type == 3 ? " selected" : "").'>Debit Card</option>
<option value="4"'.($type == 4 ? " selected" : "").'>Credit Card</option>';
Try this in your document:
<option value="1" <?php if ($type == 1) echo 'selected="selected"' ?>>Cash</option>
<option value="2" <?php if ($type == 2) echo 'selected="selected"' ?>>Cheque</option>
<option value="3" <?php if ($type == 3) echo 'selected="selected"' ?>>Debit Card</option>
<option value="4" <?php if ($type == 4) echo 'selected="selected"' ?>>Credit Card</option>'
Bear in mind that selected on its own is invalid, at least in XHTML. You might get away with it in HTML5, but personally I'd do it properly, as above. Either way, make sure you check your HTML output against the W3C validator.
Also, I tend not to wrap large blocks of HTML in PHP strings, as you have done; it is better to use HTML mode and break into PHP where dynamic output is required. This allows your IDE to understand the structure of your document, and allows syntax colouration and auto-complete to work.
Ashamed)))
sel = document.getElementById("select_id");
if($type>=0&&$type<sel.options.length)
sel.options[$type].selected=true;
do it onLoad or better onDomReady... or just after you options code. Don't forget to assign an id:
<select id="select_id">...
if you're controlling an input, then it would be JUST ONE LINE of JS:
document.getElementById("select_id").options[$type].selected=true;
You could use a function like this:
function selected($selected, $current) {
if($selected == $current)
return "selected";
}
And then:
$options = array(
1 => 'Cash',
2 => 'Cheque',
3 => 'Debit Card',
4 => 'Credit Card'
);
foreach($options as $value => $option)
echo '<option value="'.$value.'" '.selected($value, $type).'>'.$option.'</option>';
Note that the selected function is applicable in other similar cases too.
Here's how I'd do it.
$options = array(
"1"=>"Cash",
"2"=>"Cheque",
"3"=>"Debit Card",
"4"=>"Credit Card"
);
$type = $result['item'];
$type_output = "";
foreach($options as $value=>$text) {
if($value==$type){
$selected = " selected";
}
else {
$selected = "";
}
$type_output .= '<option value="'.$value.'"'.$selected.'>'.$text.'</option>';
}
Just noticed Chumkiu had a similar answer, but I'll post mine anyway in case this is clearer to some folk than the ternary if statement

JQuery/PHP: Replace a select box with another select box on a different page

On my main page, I have a simple dropdown box:
<select name="miles" id="miles">
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="75">75</option>
<option value="100">100</option>
</select>
<button type="button" name="button" id="button">Search</button>
When this button is clicked, it performs a JQuery $.load:
$("#miles").load("main_data.php #miles_data");
And here the page button is calling, main_data.php:
<?php
... code to calculate $b
?>
<span id="miles_data">
<option value="5" <?php if ($b == 5) { echo "selected"; } ?>>5</option>
<option value="10" <?php if ($b == 10) { echo "selected"; } ?>>10</option>
<option value="15" <?php if ($b == 15) { echo "selected"; } ?>>15</option>
<option value="25" <?php if ($b == 25) { echo "selected"; } ?>>25</option>
<option value="50" <?php if ($b == 50) { echo "selected"; } ?>>50</option>
<option value="75" <?php if ($b == 75) { echo "selected"; } ?>>75</option>
<option value="100" <?php if ($b == 100) { echo "selected"; } ?>>100</option>
</span>
My goals seem simple: Execute a $.load to another page, calculate an integer and set it to a variable, select the matching dropdown item and return it to the main page.
With my code above, the dropdown box on the main page becomes blank. Does anyone notice a solution?
One possible issue is that the format for a selected 'option' is:
<select>
<option>Volvo</option>
<option selected="selected">Saab</option>
<option>Mercedes</option>
<option>Audi</option>
</select>
Blatantly ripped from here
So you want to have
<option value="5" <?php if ($b == 5) { echo 'selected="selected"'; } ?>>5</option>

Categories