Select form - use last posted value if blank - php

Sorry in advance for the novice question here...
I currently have my first value as a disabled and defaulted "Select" option which then changes to the selected option when a selection is made.
However if the user submits again without reselecting, the value defaults back because the post is blank. Therefore is there a way to use the previous value if so?
<select name="test_select" style="width: 110px">
<option disabled="disabled" selected="selected">
<?php
if(!empty($_POST['test_select'])){
echo $_POST[test_select'];}
else
echo "Select Option"; ?>
</option>
<?php $sql = mysql_query("SELECT test FROM test_settings");
while ($row = mysql_fetch_array($sql)){
?><option><?php echo $row['test']; ?></option><?php }?>
</select>
Thanks in advance,
Dan

I suppose that problem is that forms are not sending disabled values.
I would edit code as following:
<select name="test_select" style="width: 110px">
<?php
if (empty($_POST['test_select']))
echo '<option selected="selected">Select Option</option>';
$sql = mysql_query("SELECT test FROM test_settings");
while ($row = mysql_fetch_array($sql)){
$selected = isset($_POST['test_select']) && $row['test'] == $_POST['test_select']
? ' selected="selected"'
: '';
echo '<option'.$selected.'>'.$row['test'].'</option>';
?>
</select>

Related

Retain selected option after form submitted

I have the following code that get some options from database using php and mysql
<select class="form-control" id="Type" name="Type">
<option></option>
<?php
$TypeQuery = "SELECT DISTINCT Type FROM Details";
$TypeQueryExecute = mysqli_query($conn, $TypeQuery);
while($TypeQueryRow = mysqli_fetch_array($TypeQueryExecute)){
$Type = $TypeQueryRow['Type'];
echo "<option value='{$Type}'>{$Type}</option>";
}
?>
</select>
I want to retain the dropdown list selection after form submission. I am using php $_POST[''] method for form submission. I tried the following way. But it is not working.
<select class="form-control" id="Type" name="Type">
<option></option>
<?php
$TypeQuery = "SELECT DISTINCT Type FROM oaDetails";
$TypeQueryExecute = mysqli_query($conn, $TypeQuery);
while($TypeQueryRow = mysqli_fetch_array($TypeQueryExecute)){
$Type = $TypeQueryRow['Type'];
?>
<option <?php if ($_POST['Type']==$Type) echo 'selected="selected"'; ?> >
<?php echo $Type; ?>
</option>
<?php
}
?>
</select>
Does anyone know what am I doing wrong here?
Edit 1
I tried the following way. Now it is not showing any options. Instead some errors
<option value=<?php echo $_POST['Type']; ?> <?php if ($_POST['Type'] == $Type) echo 'selected="selected"'; ?> ><?php echo $_POST['Type']; ?></option>
Edit 2
I tried following way and this time it is retaining the values. But only thing is if I select an option with spacing in between and click submit, the value is not retaining and just go to default blank. You can see what I mean by option with spacing as below
Options with no space as below retaining and working well as per my need
You are missing some quotes in your output HTML, that's why spaces in the value throw you out. It should be
<option value="<?php echo $_POST['Type']; ?>" <?php if ($_POST['Type'] == $Type) echo 'selected="selected"'; ?> ><?php echo $_POST['Type']; ?></option>

isset($_POST['tag-name']) is set but $_POST['tag-name'] return empty when selecting dynamic list

I has created dynamic list in php.
<select name="student" >
<option selected disable class="hideoption">Student Name</option>
<?php
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo<option value='".$row['path']."'>'".$row['studentName']."'</option>";
}
?>
</select>
When I'm selected the list it give empty string. But when I'm not selected anything it return the first value which is Student Name. I tried to get the value from this line.
if(isset($_POST['student'])){
$selectedName = $_POST['student'];
}
I also try to checked whether the isset is set or empty. The isset is set but its empty.
This is the only solution Google provided.Ideas?
Edit
I have solved the problem. The explanation on the answer below.
At first I thought $_POST['student'] returning the text inside the <option> tag and I was wrong. I learnt that it return the value which is should be set in <option> attribute, So I just set the value to $row['studentName'], because $row['path'] returned empty string. Correct me if what I said is wrong. So basically, the code looks like below.
<select name="student" >
<option selected disable class="hideoption">Student Name</option>
<?php
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo<option value='".$row['studentName']."'>'".$row['studentName']."'</option>";
}
?>
</select>
Thanks for all your responses. Your responses made me think what should I do.
Use below code:
<select name="student" id="student" >
<option selected disable class="hideoption">Student Name</option>
<?php
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo "<option name='".$row['studentName']."' value='".$row['path']."'>'".$row['studentName']."'</option>";
}?>
</select>
You should be use this line isset($_POST['studentName']) && $selected = $_POST['studentName'] == $row['studentName'] ? 'selected = "selected"' : null; for selected option
<select name="student" >
<option selected disable class="hideoption">Student Name</option>
<?php
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
$selected = isset($_POST['studentName']) && $_POST['studentName'] == $row['studentName'] ? 'selected = "selected"' : null;
echo "<option ".$selected." value='".$row['path']."'>".$row['studentName']."</option>";
}
?>
</select>
#dongcheng This is the same code but with better alignments. So you can see your code clearly.
<select name="student">
<option selected disable class="hideoption">Student Name</option>
<?php
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
echo '<option value="' . $row['path'] . '">' . $row['studentName'] . '</option>';
}
?>
</select>
use
$selectedStudent = !empty($_POST['student']) ? $_POST['student'] : '';
if ($selectedStudent) {
// your code
}

how to set the selected value tag <select> html from database in php?

I'm trying to create a drop down menu that will select a value that is stored in the database. here's the code :
require 'koneksi.php';
$sql_select = "SELECT * FROM supplier";
$hasil = mysql_query($sql_select);
if(!$hasil) {
echo "data supplier not found ".mysql_error();
}
$id = $_GET["id"];
$hasil2 = mysql_query("SELECT * FROM brg_supplier WHERE id_brg=".$id);
$data = mysql_fetch_array($hasil2);
if($hasil2) {
$supplier = $data['nama_supplier'];
}
<select name="supplier">
<option value="">---pilih supplier---</option>
<?php
while($baris = mysql_fetch_array($hasil)){
?>
<option value="<?php $baris['nama_supplier'] ?>" <?php if ($supplier==$baris['nama_supplier']) echo 'selected="selected"'; ?> > <?php echo $baris['nama_supplier']; ?> </option>;
<?php }?>
</select>
the problem is my code creates a dropdown with nothing selected. here's the screenshot : link
i've tried all the solutions in the stackoverflow. but the dropdown value still nothing selected. i know that it has to be something simple that i am missing but seriously i cannot figure it out. please anyone help, thanks!
I think the problem lies in this line:
<option value="<?php $baris['nama_supplier'] ?>" <?php if ($supplier==$baris['nama_supplier']) echo 'selected="selected"'; ?> > <?php echo $baris['nama_supplier']; ?> </option>;
You're missing an echo and it looks funny :/
Try instead:
<option <?php $val=$baris['nama_supplier']; echo "value='$val'"; if($supplier==$val) echo "selected='selected'>";echo $val;?> </option>;
Try this way..
$sel="select f.*,c.category from final f, category c where f.category_id=c.id and f.id='$id'";
$data=mysql_query($sel);
$res=mysql_fetch_assoc($data);
<select name="cat">
<?php
$sql = mysql_query("SELECT * FROM category");
while ($row = mysql_fetch_array($sql)){
if($row['id'] == $res['category_id']){
echo '<option value="'.$row['id'].'" selected="selected">'.$row['category'].'</option>';
}else{
echo '<option value="'.$row['id'].'">'.$row['category'].'</option>';
}
}
?>
</select>
Try this out
require 'koneksi.php';
$sql_select = "SELECT * FROM supplier";
$hasil = mysql_query($sql_select);
if(!$hasil) {
echo "data supplier not found ".mysql_error();
}
$id = $_GET["id"];
$hasil2 = mysql_query("SELECT * FROM brg_supplier WHERE id_brg=".$id);
$data = mysql_fetch_array($hasil2);
if(mysql_num_rows($hasil2) > 0) {
$supplier = $data['nama_supplier'];
}
<select name="supplier">
<option value="">---pilih supplier---</option>
<?php
while($baris = mysql_fetch_array($hasil)){
?>
<option value="<?php echo $baris['nama_supplier'] ?>" <?php if ($supplier==$baris['nama_supplier']) {echo 'selected="selected"';} ?> > <?php echo $baris['nama_supplier']; ?> </option>;
<?php }?>
</select>
<option value="<?php $baris['nama_supplier'] ?>
should be
<option value="<?php echo $baris['nama_supplier'] ?>
I spent some time trying to find the best solution for this, and came up with a tiny little jQuery code.
First of all you should be using PDO or mysqli instead of mysql, since it's deprecated. Let's assume you've fixed that.
Inside the <form> tag, add an <input type="hidden"/> so that it can storage your database value, for example:
HTML
<form>
<input id="valueFromDatabase" type="hidden" value="<?php echo $stringFromDB ?>"/>
</form>
Note: in this case, $stringFromDB is a variable that holds your query's return from DB.
So now we have the value of our database inside our HTML code. Now we just need to check if any of the options inside the <select> tag is equal to this value. We'll be doing it with jQuery:
jQuery
$( document ).ready(function() {
$('option').each(function(){
if (this.value == $('#valueFromDatabase').val()){
this.setAttribute('selected', 'selected');
}
});
});
What's happening here? We are telling to jQuery to analyze all the <option> tags in the HTML and compare its value with our value from database; if its equal, we add the selected attribute to the equivalent <option>.
You can it working here (used a calendar example).
Hope that helps!

Show selected value in dropdown after submit

hi guys i added dropdown field to form however after i submit the form if there is any error dropdown resets itself how can keep to value after validation thanks a lot for your any helps and idea
here is my code
<td><select id="country" name="country" style="width:150px;">
<option value="-1">Select</option>
<?php
$query = "SELECT country_id, name FROM countries ";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
echo "<option value=\"".$row['country_id']."\" >".$row['name']."</option>\n ";
}
?>
</select></td>
<td><?php echo $form->error("country"); ?></td>
Typically you would set the default option with attribute selected that is tied to the current selected value. So in this case, the option that equals the value of $_POST['country']:
while ($row = mysql_fetch_array($result))
{
if ($row['country_id'] == $_POST['country'])
$selected = "selected=\"selected\"";
else
$selected = "";
echo "<option value=\"".$row['country_id']."\" $selected>".$row['name']."</option>\n ";
}
Which would render as the following on the appropriate option:
<option value="123" selected="selected">456</option>

display from database to dropdown list

I have stored value from drop down list to database. I want to echo the same value to be displayed in that drop down list in my edit form. how can I achieve that in php?
Region
<select name="stf_region">
<option>Select</option>
<option value="1">MDU</option>
<option value="2">TMM</option>
</select>
i have stored in database using value of selection
but i dont know to display that value in same drop down
Use something like this:
<?
$sql = "SELECT id, description FROM dropDownTable";
$rs = mysql_query($sql);
?>
<select name="dropDown">
<option value="-1">Please select...</option>
<? while ($obj = mysql_fetch_object($rs)) { ?>
<option value="<?= $obj->id; ?>" <? if ($data['downDown'] == $obj->id) echo "SELECTED"; ?>>
<?= $obj->description; ?>
</option>
<? } ?>
</select>
Please note $data needs to be set as an associative array containing attributes of the entity that is being edited. This code is flexible because in the case of a form where a user may have submitted an incomplete form $data could be set to the $_POST variable and so all entered fields can be included without the user needing to re-specify fields they previously filled in. This basically means your form template, inserting an entry and editing an entry can be the same!
Well you could do like this
$query = "select id, label from lookup_table";
$result = mysql_query($query);
$html = "<select name='yourname'><option value="">Please select...</option>";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$html .= "<option value='$row[id]'>$row[label]</option>";
}
$html = "</select>";
echo ($html);//Display the select in the page
If you're able to get db data into array, you can work with them like this:
<?php
$options = array('label 1' => 'value 1', 'label 2' => 'value 2');
echo "<select name=somename>";
foreach($options as $key => $value){
echo "<option value=" . $value . ">" . $key . "</option>";
}
echo "</select>";
?>
i used the COOKIE to match the value that should be selected when it comes to edit the form.
<?php
while($result_row=mysql_fetch_array($result)){
if ( $_COOKIE['MY_COOKIE'] == $result_row[importance_level_id )
{
echo "<option SELECTED=\"SELECTED\" value=$result_row[importance_level_id]>$result_row[importance_level]</option>";
}
else
{
echo "<option value=$result_row[importance_level_id]>$result_row[importance_level]</option>";
}
?>
Assuming you are ok with selecting the value out of the database into a PHP variable (let's say $region) I think you are just after
Region
<select name="stf_region">
<option>Select</option>
<option value="1"<?php echo ($region == '1') ? ' selected="selected"' : ''; ?>>MDU</option>
<option value="2"<?php echo ($region == '2') ? ' selected="selected"' : ''; ?>>TMM</option>
</select>
This is the most concise answer to the question that I think you are asking. However this is a very specific answer and assumes that your dropdown values are hard-coded and won't really be changing.
If you want a more flexible setup that retrieves the values of the dropdown from the database you are looking for something more along the lines of what has been suggested by Gordon Murray Dent above
<div class="form-group has-success col-md-6">
<label class="control-label" for="state-success">Select Buyer</label>
<select id="state-success" class="form-control ">
<?php
$sql="SELECT full_name FROM `new_customer`";
$data=mysqli_query($dbcon,$sql);
?>
<option>Select byer...</option>
<?php while($row1=mysqli_fetch_array($data)){?>
<option value="<?php echo $row1['full_name'];?>"><?php echo $row1['full_name'];?></option>
<?php } ?>
</select>

Categories