Defining selected option of html form in PHP - php

I have a simple html form with select element. To define which option is selected, I add selected as
<option value="10" <?php if($value == '10') {echo 'selected="selected"';}?>>10</option>
<option value="20" <?php if($value == '20') {echo 'selected="selected"';}?>>20</option>
<option value="50" <?php if($value == '50') {echo 'selected="selected"';}?>>50</option>
$value is a variable which comes from PHP codes. This methods seems to be very simple and naive. Is it the best way to do so?

$options = array(10,20,50);
foreach($options as $option) {
$selected = ($value == $option) ? ' selected="selected"' : '';
echo '<option value="' . $option . '"' . $selected . '>' . $option . '</option>';
}

Not a bad way to do it. But why not create the entire thing using programmatic approach (i.e., generate the code using a PHP loop through an array):
$items = array(10, 20, 50);
for ($i = 0; $i < count($items); $i ++) {
echo("<option value='" . $items[$i] . "'");
if ($items[$i] === $value) {
echo(" selected='selected'");
}
echo(">" . $items[$i] . "</option>");
}

Something along the lines of the below should work:
<?
$values = array(10, 20, 30);
foreach ($values as $val) {
?>
<option value="<?=$val?>" <?=($value==$val ? "SELECTED" : "")?>><?=$val?></option>
<?
}
?>

Keep your values in an array and loop over it to generate the HTML. Then you don't need to repeat yourself.

<?php foreach($list as $key => $value): ?>
<option value=<?php echo $value ?> <?php echo $value == $selected? 'selected' : '' ?> ><?php echo $value ?></option>
<?php endforeach ?>
Hope you get the idea.

This is the like i do it:
<?
$values = array(10,20,30,......);
$value = XXX;
echo "<select name='somename'>";
foreach($values as $v)
{
if($v == $value)
{
echo "<option value='$v' 'selected'>$v </option>";
}
else
{
echo "<option value='$v'>$v </ option> ";
}
}
echo "</select>";
?>

Related

How to post data from dropdown to filter table in PHP?

I'm printing CSV file on a webpage, the following code reads the file from the directory and displays data in table format this part works really well.
But I need to filter this table with the help of two dropdowns one has session id and the second one is the start date.
The problem is I'm not able to pass the value from these two dropdowns to the the if ($v[0] != $session && $row > 0) continue; where $v[] may have index 0 or 1 and $session has value from dropdowns.
<?php
$dir = 'uploads/';
$files = scandir($dir);
?>
<form name="form1" method="post">
<select class="form-control col-sm-5" onChange="document.forms['form1'].submit()" id="chooseterm" name="chooseterm">
<option value="" selected>Choose Term</option>
<?php
foreach ($files as &$value) {
echo '<option value="' . $value . '">' . $value . '</option>';
}
?>
</select>
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$t = $_POST["chooseterm"];
$filepath = "uploads/$t";
$row = 0;
$the_big_array = [];
$unique_start_date = [];
$unique_ids = array();
if (($h = fopen("{$filepath}", "r")) !== false) {
while (($data = fgetcsv($h, 1000, ",")) !== false) {
$the_big_array[] = $data;
$unique_ids[$data[0]] = true;
$unique_start_date[$data[1]] = true;
}
fclose($h);
}
?>
<select class="form-control col-sm-5" onChange="document.forms['form1'].submit()" id="choosessionid" name="choosessionid">
<?php foreach ($unique_ids as $k => $v) {echo '<option value="' . $k . '">' . $k . '</option>';}?>
</select>
<select class="form-control col-sm-5" onChange="document.forms['form1'].submit()" id="session_start_date" name="session_start_date">
<?php foreach ($unique_start_date as $k => $v) {echo '<option value="' . $k . '">' . $k . '</option>';}?>
</select>
</form>
<table class="table">
<tbody>
<?php
array_shift($the_big_array);
$temp = '';
foreach ($the_big_array as $k => $v) {
if (isset($_POST['choosessionid']) || ($_POST['session_start_date']) ) {
$session_start_date = '';
$session = '';
if (isset($_POST['choosessionid'])){
$session = $_POST['choosessionid'];
if ($v[0] != $session && $row > 0) continue;
}
if (isset($_POST['session_start_date'])){
$session = $_POST['session_start_date'];
if ($v[1] != $session && $row > 0) continue;
}
} //at $session I need values from dropdown choosessionid OR session_start_date else show all the results
$row++;
?>
<?="<tr>"; ?>
<?="<td>" . $v[0] . "</td>"; ?>
<?="<td>" . $v[1] . "</td>"; ?>
<?="<td>" . $v[2] . "</td>"; ?>
<?="<td>" . $v[3] . "</td>"; ?>
<?="</tr>"; ?>
<?php } ?>
</tbody>
</table>
<?php
}
?>

PHP - remember input selection option

I'm trying to translate a Java 'calculator' I wrote to PHP/HMTL. To get this to function the initial selection has to be remebered. I know I need to use $_POST['subject'] to get $cc this however causes a problem for me.
I tried several versions but I fear I lack some basics. Is anyone able to push me in the right direction?
Code without remember option:
<form action="" method="post">
<legend>Make a selection below</legend>
<br>
Field of interest:<br>
<select name="subject">
<?php
$subjectarray = array("Please select a subject", "Wavelenght", "Radioactive Decay");
foreach ($subjectarray as $cc => $subject) {
echo '<option value="' . $cc . '">' . $subject . '</option>';
}
?>
</select>
Code with a version of the remember option (clearly not working);
foreach ($subjectarray as $cc => $subject) {
echo '<option value="' . $cc . '"
if ($_POST['subject'] == $cc) echo 'selected="selected"';>' . $subject . '</option>';
}
Another try
foreach ($subjectarray as $cc => $subject) {
echo "<option value=\"{$cc}\"";
echo ($_GET['subject'] == $cc) ? 'selected="selected"' :"";
echo ">" . $subject . "</option>";
}
How about:
<select name="subject">
<?php
foreach(["Please select a subject", "Wavelenght", "Radioactive Decay"] as $i => $val) {
$sel = empty($_POST['subject']) || $_POST['subject'] != $i ? null : 'selected';
?>
<option <?= $sel ?> value="<?= $i ?>"><?= $val ?></option>
<?php } ?>
</select>
Note:- you have to use $_POST['subject'] because method='POST' in form Tag.
You need to foreach through all the options.
Make an array with all the dropdown options, loop through that, and compare with what is stored in $_POST[] & just put the selected attribute on the one which you want to select.
<form action="" method="post">
<legend>Make a selection below</legend>
<br>Field of interest:<br>
<select name="subject">
<?php
$subjectarray = array("Please select a subject", "Wavelenght", "Radioactive Decay");
foreach ($subjectarray as $cc => $subject) {
if ($_POST['subject'] == $cc) {
$selected = 'selected';
} else {
$selected = '';
}
echo '<option value="' . $cc . '" '.$selected.'>' . $subject . '</option>';
}
?>
</select>
</form>
Second option is using $_GET and you are using POST in the form. It'll never work.
The first one looks like it'll throw an error... Not a valid syntax in PHP. In PHP you can't have if inside an echo or print.
What I like to do is(rewriting your foreach):
foreach ($subjectarray as $cc => $subject) {
$selected = $_POST['subject'] == $cc ? ' selected="selected"' : '';
echo '<option value="' . $cc . '"'. $selected .'>' . $subject . '</option>';
}

Selecting an item in select(dropdown) box using php

<form method="post" action="#">
<select name="select">
<?php
foreach($stock as $key => $value):
echo '<option value="'.$value.'">'.$value.'</option>';
endforeach;
?>
<option selected="selected" value="<?php echo $search; ?>"><?php echo $search; ?> </option>
</select>
This code adds a new value to the select box at last. But I need to select a value which is already present in the select box.
Eg, It contains a,b,c,d
I need to select c, but when i use this code it becomes a,b,c,d,c and the last "c" is selected.
Any ideas ?
Check in your loop if the value matches the search. So instead of:
<?php
foreach($stock as $key => $value):
echo '<option value="'.$value.'">'.$value.'</option>';
endforeach;
?>
Do:
<?php
foreach($stock as $key => $value)
{
if($search == $value)
echo '<option value="'.$value.'" selected="selected">'.$value.'</option>';
else
echo '<option value="'.$value.'">'.$value.'</option>';
}
?>
it will help
<select name="select">
<?php
foreach($stock as $key => $value)
{
// This test printing value
$option_selected = "";
if($search == $value){
$option_selected = 'selected="selected"';
}
echo '<option value="'.$value.'" '.$option_selected.'>'.$value.'</option>';
}
?>
</select>
try
<form method="post" action="#">
<select name="select">
<?php
$q = "";
foreach($stock as $key => $value):
if($search = $value ){
$p = '<option selected="selected" value="'.$search.'">'.$search.'</option>';
}
$q = .'<option value="'.$value.'">'.$value.'</option>';
endforeach;
?>
echo $p;
echo $q;
<html>
<select name="selectu">
<?php
$html = '';
$html1 = '';
$html2 = '';
foreach ($stock as $key => $value):
if ($value == $search):
$html1 = '<option value="' . $value . '" selected="selected">' . $value . '</option>';
else:
$html2 .= '<option value="' . $value . '" >' . $value . '</option>';
endif;
endforeach;
echo $html = $html1 . $html2;
?>
</select>

mySql fetch array ignore null value

Here i am populating my dropdowns with database fields using php
my code follows,
while ($row = mysql_fetch_array($result)) {
$series1 .= "<option id='Series1' value='" . $row['Series'] ."'>" . $row['Series'] ." </option>";
}
after fetching i echo it to html
<select id="Series1" onchange="changeVal('Series1')">
<option value="">Please select</option>
<?php echo $series1 ?>
</select>
my problem is i have some null values in the database field, i don't want that to be inserted in the options field. my final result now look like this
please help me.
Try this
while ($row = mysql_fetch_array($result)) {
if($row['Series'] != '' || $row['Series'] != NULL) {
$series1 .= "<option id='Series1' value='" . $row['Series'] ."'>" . $row['Series'] ." </option>";
}
}
OR
In your sql query
SELECT * FROM your_table WHERE Series IS NOT NULL
You can try like this
while ($row = mysql_fetch_array($result)) {
if(isset($row['Series'])) {
$series1 .= "<option id='Series1' value='" . $row['Series'] ."'>" . $row['Series'] ." </option>";
}
}
Try this...
<select id="Series1" onchange="changeVal('Series1')">
<option value="">Please select</option>
<?php
while ($row = mysql_fetch_array($result))
{
if($row['Series'] != '' || $row['Series'] != NULL)
{
?>
<option value="<?php echo $row['Series']; ?>"><?php echo $row['Series']; ?></option>
</select>
<?php
}
}
?>

PHP for each drop down selected

I got this piece of code here...
<form action="InvoiceNotice.php?action=invoicenotice" method="post">
<label for="fordays">Select Day</label>
<select name="daySelected" id="daySelected">
<option value="0">Today</option>
<?php
$array = array_combine(range(1,$InvoiceDaysArray['days']), range(1,$InvoiceDaysArray['days']));
foreach($array as $row => $value){
$selected = '';
$daySelected = 0;
if($daySelected == $row){
$selected = 'SELECTED';
}
echo "<option selected='" . $selected . "' value='" . $row . "'>" . $value . " days ago</option>";
}
?>
</select>
<input type="submit" name="button" id="button" value="Submit" />
</form>
My issue is with the $selected the $daysSelected variable comes from what has been selected. What I am trying to do is when a user selects an option, that option is now selected in the dropdown and the page returns, after the client hits submit.
Does any one know what I am talking about?
Thanks
I would do something like:
foreach($array as $row => $value){
$selected = '';
if($_POST['daySelected'] == $row){
$selected = ' selected="selected"';
}
echo "<option" . $selected . " value='" . $row . "'>" . $value . " days ago</option>";
}
Although you probably only need selected instead of selected="selected".
I see some problems in your code:
first you are setting $daySelected = 0; and then try compare with variable from database, day 0 is not in your foreach loop try this
<form action="InvoiceNotice.php?action=invoicenotice" method="post">
<label for="fordays">Select Day</label>
<select name="daySelected" id="daySelected">
<option value="0">Today</option>
<?php
$array = array_combine(range(1,$InvoiceDaysArray['days']), range(1,$InvoiceDaysArray['days']));
foreach($array as $row => $value){
$selected = '';
$daySelected = $_POST['daySelected'];
if($daySelected == $row){
$selected = "selected=SELECTED";
}else {$selected='';}
echo "<option '" . $selected . "' value='" . $row . "'>" . $value . " days ago</option>";
}
?>
</select>
<input type="submit" name="button" id="button" value="Submit" />
</form>

Categories