Using PHP $_POST to remember a option in a select box? - php

I have a form which POSTs to itselft so the user can do things that you would find in a Shopping Cart.
e.g. Increase quantity, select postage type.
My problem is for my form Select element called "postage" whenever the form reloads itself , it forgets what was selected.
All my other fields remember their values using this:
<input type="text" name="postcode" value="<?php echo $_POST['postcode']; ?> " />
How do I use the $_POST value to automatically select the option in the select field that was done by the user?
I tried this:
<select name="postage" selected="<?php echo $_POST['postage']; ?>" >
and this
<select name="postage" value="<?php echo $_POST['postage']; ?>" >
Thanks

You almost got it. You need to set the attribute selected="selected" (the exact form you need technically depends on your HTML doctype, but this is a safe default) on the <option> element if and only if the value of $postage equals the value of the element. So:
<select name="postage">
<option value="foo"
<?php if ($_POST['postage'] == "foo") echo 'selected="selected" '; ?>
>
</select>
Note that this violates the DRY principle because you now have two occurrences of the string "foo" in there, so it's a prime candidate for refactoring. A good approach would be to keep value/text pairs in an array and iterate over it with foreach to produce the <option> tags.

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.
E.G.:
<?php
$aDropd = array("apple","orange","banana");
echo "<select>";
foreach($aDropd as $sOption){
$sSel = ($sOption == $_POST['postage'])? "Selected='selected'":"";
echo "<option $sSel>$sOption</option>";
}
echo "</select>";

no its not working at all..you need to put some kind of loop for that.
For Example : foreach($record => $values){
if($values == $_POST['postage']){
$selected = "selected='selected' ";
}else{
$selected = "";
}
}
<input name="postage" value="1" <?=$selected?> >
EDITED:
if($_POST['postage'] == 1){
$selected1 = "selected='selected' ";
}else if($_POST['postage'] == 2){
$selected2 = "selected='selected' ";
} and so on..........
<select name="postage">
<option value="1" <?=$selected1;?> />
<option value="2" <?=$selected2;?> />
</select>
I think this may be helpful to you..you can ask me if anything else needed...
Thanks.

The value of selected should be selected
<select name="postage" value="1" <?php echo (($_POST['postage'] == 1)?'selected="selected"':''); ?> >

Your html syntax is wrong. The correct way to write the html is like this:
<select>
<option value ="<?php echo $_POST['postage']; ?>" selected="selected"></option>
</select>

You can also make it shorter:
<select>
<option value ="<?=$_POST['postage']; ?>" selected="selected"></option>
</select>

<select name="foo">
<option value="1" <?php echo strcmp($_POST['foo'],"1")==0?"selected=\"selected\"":"" ?>>option1</option>
<option value="2" <?php echo strcmp($_POST['foo'],"2")==0?"selected=\"selected\"":"" ?>>option2</option>

Related

Get the value from database in selecte tag HTML PHP MySQL [duplicate]

This question already has an answer here:
Select option default based on database variable [duplicate]
(1 answer)
Closed 7 years ago.
I'm beginner in PHP MySQL. I successfully get the value from database in INPUT type but I can't get the data from database in SELECT type:
Here is my sample edit form where Gender & User Type can't output the value from my database:
and here is data from the table I created:
I'm calling the data in my input box by using this code:
<?php $userRow['agentFname']; ?> //$userRow['ROW NAME IN TABLE'];
But I can't call the data where In select box, like Gender: and User Type here is my code of Select box.
<select class="form-control" name="aGender" >
<option selected disabled>*Gender</option>
<option>Male</option>
<option>Female</option>
</select>
<select class="form-control" name="utype" >
<option selected disabled>*User Type</option>
<option>Agent</option>
<option>Team Leader</option>
<option>Admin</option>
</select>
#Edmhar has a good answer, but it is hard coded and isn't good if you want to add more genders (transgenders and what not).
What I do is something like this:
<?php
$array = array("male", "female", "other");
echo "<select class='form-control' name='aGender' >";
foreach ($array as $gender) {
if ($gender == $databaseValue) {
echo "<option selected>$gender</option>";
} else {
echo "<option>$gender</option>";
}
}
echo "</select>";
?>
Also, don't use disabled on form elements; use read-only. It does the same thing as disabled visually, but disabled does what it says. It blocks the value from being submitted to the database. read-only just prevents editing, but doesn't cause form submission problems. User type will follow the same suit.
I already have my own answer to this
Here how I solved this:
<select class="form-control" name="aGender" >
<?php
if ($userRow['agentGender'] == 'Male') {
echo "<option selected>Male</option>";
echo "<option>Female</option>";
} else {
echo "<option selected>Female</option>";
echo "<option>Male</option>";
}
?>
</select>
I think you can use below conditional code for this issue:
<?php if($userRow['aGender'] == 'Male'){
$selectedMale = 'selected="selected"'
$selectedFemale = ''
}else{
$selectedFemale = 'selected="selected"'
$selectedMale = ''
}?>
<select class="form-control" name="aGender" >
<option selected disabled>*Gender</option>
<option <?php echo $selectedMale ;?>>Male</option>
<option <?php echo $selectedFemale;?>>Female</option>
</select>
and same for the another select box.
It will work hopefully.
In my opinion it's best to use ternary operator in such a case, combined with options element fetched from db/array. Something like:
<?php $options = Array(1 => "Option 1", 2 => "Option 2")
<select>
<?php foreach($options as $key => $opt): ?>
<option value="<?= $key ?>" ($key == $userRow['value'] ? "selected" : "" )><?= $opt ?></option>
<?php endforeach; ?>
</select>

<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

select dropdown value based on session variable

i have a php form which submits data to another php for validation. if any fields are left blank the validator php sends a message back to original php form along with all the pre filled variables using session variables so that user doesn't have to fill them again.
i can use these session variables to fill in text boxes again like this
value="<?php echo $_SESSION['fname'] ?>"
but how to go about populating drop downs, radio buttons and check boxes?
thanks
For a select, checkbox or radio box you would need to check whether the values match. Something like:
<select name="fname">
<option value="1" <?php if($_SESSION['fname'] == 1) echo 'selected'; ?>>1</option>
<option value="2" <?php if($_SESSION['fname'] == 2) echo 'selected'; ?>>2</option>
</select>
It's easier if you are iterating through the values for the option field:
<select name="fname">
<?php foreach($array AS $key => $value) { ?>
<option value="<?php echo $value; ?>" <?php if($_SESSION['fname'] == $value) echo 'selected'; ?>><?php echo $value; ?></option>
<?php } ?>
</select>
A <select> element's selected <option> is not determined by it's value= attribute. In order to mark an option selected, the <option> element must have the selected attribute set on it, as follows:
<select>
<option>1</option>
<option selected>2</option>
<option>3</option>
</select>
In order to do this programmatically, you need to iterate through the options, and manually test for the correct option, and add selected to that.
... Noticed that your double quote at the end of the statement was misplaced, it should be:
<script>
$("#fname").val("<?php echo $_SESSION['fname'] ?>");
</script>
There is a far simpler method using JQuery. You can set Selects with .val() so make the most of it.
<script type="text/javascript">
$("#fname").val("<?php echo $_SESSION['fname']; ?>");
</script>
Don't forget to set the id of the select as well as the name to fname.

passing parameters to html select from php

I would like to pass php parameters to an html select options tag. it works fine for an input tag using the value attribute as follows:
<input type="text" name="to" value= "<?php echo $parameter ?>" size=10>
I tried to do the same for the select tag, but some reason its not working. Below is the select tag:
<select name="clinic">
<option value="<?php echo $clinicName; ?>" >Baylor</option>
<option value="<?php echo $clinicName; ?>" >IDCC</option>
</select>
Please note that the parameter would need to passed to an sql statement below these above statements as follows:
$clinicName = $_POST['clinic'];
$sql = "select * from patients where clinic = '$clinicName'";
Should do the trick
<select name="clinic">
<option <?php echo ($clinicName=="Baylor" ? "selected" : ""; ?> value="Baylor">Baylor</option>
<option <?php echo ($clinicName=="IDCC" ? "selected" : ""; ?> value="IDCC">IDCC</option>
</select>
Also, as someone above me mentioned in the comments, you need to read up on SQLi otherwise your site is just one more to the list of already-hacked.
Are you trying to set the current selected value on the <select>? If so, you need to use if statements to check which one to mark as selected:
<option value="Baylor"<?php if($clinicName == 'Baylor') echo ' "selected"'?>>Baylor</option>
<option value="IDCC"<?php if($clinicName == 'IDCC') echo ' "selected"'?>>IDCC</option>
Instead of the if, you could also use the ternary operator:
<option value="Baylor"<?php echo $clinicName == 'Baylor' ? ' "selected"' : ''?>>Baylor</option>
<option value="IDCC"<?php echo $clinicName == 'IDCC') ? ' "selected"' : ''?>>IDCC</option>
First of all, please sanitize your SQL query. Right now it is more exploitable than Lindsay Lohan. If you use mysql_* functions, then write it as:
$sql = "select * from patients where clinic = '".mysql_real_escape_string($clinicName)."'";
Secondly, in your HTML the $clinicName is the same on both cases. So the $_POST['clinic'] will always be the same no matter what. If you want to pre-select a value, then you need to write it as:
<select name="clinic">
<option value="Baylor" <?php if($clinicName=='Baylor'){ echo 'selected'; } ?>>Baylor</option>
<option value="IDCC" <?php if($clinicName=='IDCC'){ echo 'selected'; } ?>>IDCC</option>
</select>
Other than that, I remain a bit confused about your question.
Copy this in your HTML tag
<select name="clinic">
<option value="baylor" >Baylor</option>
<option value="IDCC" >IDCC</option></select>
And this before your HTML tag
<?php
echo $clinicName = $_POST['clinic'];
?>

How to Keep the selected value of the select box after Form POST or GET

Im trying to implement the search feature in my website.
when the search keyword is entered in the textbox, and the category combo is selected, the form will be Posted and the result will be shown on the same page.
what i want is to keep the selected category of the combo by default in the form after posted
For eg., If i select the category 'Automobiles' in the combo and click search, after form submit, the combo should show the automobiles as default selected option. Please help me. Any help will be appreciated
I assume you get categories from database.
you should try:
<?php
$categories = $rows; //array from database
foreach($rows as $row){
if($row['name'] == $_POST['category']){
$isSelected = ' selected="selected"'; // if the option submited in form is as same as this row we add the selected tag
} else {
$isSelected = ''; // else we remove any tag
}
echo "<option value='".$row['id']."'".$isSelected.">".$row['name']."</option>";
}
?>
Assuming that by "combo" you mean "A regular select element rendering as a drop down menu or list box" and not "A combobox that is a combination of a drop down menu and free text input":
When outputting the <option> elements, check the value against the submitted data in $_POST / $_GET and output selected (in HTML) or selected="selected" (in XHTML) as an attribute of the option element.
Here is the JQuery way I am using.
<select name="name" id="name">
<option value="a">a</option>
<option value="b">b</option>
</select>
<script type="text/javascript">
$("#name").val("<?php echo $_POST['name'];?>");
</script>
But this is only if you have jquery included in your webpage.
Regards
<?php
$example = $_POST["friend"];
?>
<form method="POST">
<select name="friend">
<option value="tom" <?php if (isset($example) && $example=="tom") echo ' selected';?>>Thomas Finnegan</option>
<option value="anna" <?php if (isset($example) && $example=="anna") echo ' selected';?>>Anna Karenina</option>
</select>
<br><br>
<input type="submit">
</form>
This solved my problem.
This Solved my Problem. Thanks for all those answered
<select name="name" id="name">
<option value="a">a</option>
<option value="b">b</option>
</select>
<script type="text/javascript">
document.getElementById('name').value = "<?php echo $_GET['name'];?>";
</script>
$countries_uid = $_POST['countries_uid'];
while($row = mysql_fetch_array($result)){
$uid = $row['uid'];
$country = $row['country_name'];
$isSelected = null;
if(!empty($countries_uid)){
foreach($countries_uid as $country_uid){//cycle through country_uid
if($row['uid'] == $country_uid){
$isSelected = 'selected="selected"'; // if the option submited in form is as same as this row we add the selected
}
}
}else {
$isSelected = ''; // else we remove any tag
}
echo "<option value='".$uid."'".$isSelected.">".$country."</option>";
}
this is my solutions of multiple select dropdown box after modifying Mihai Iorga codes
After trying al this "solves" nothing work. Did some research on w3school before and remember there was explanation of keeping values about radio. But it also works for Select option. See here an example. Just try it out and play with it.
<?php
$example = $_POST["example"];
?>
<form method="post">
<select name="example">
<option <?php if (isset($example) && $example=="a") echo "selected";?>>a</option>
<option <?php if (isset($example) && $example=="b") echo "selected";?>>b</option>
<option <?php if (isset($example) && $example=="c") echo "selected";?>>c</option>
</select>
<input type="submit" name="submit" value="submit" />
</form>
Easy solution:
If select box values fetched from DB then to keep selected value after form submit OR form POST
<select name="country" id="country">
<?php $countries = $wpdb->get_results( 'SELECT * FROM countries' ); ?>
<option value="">
<?php if(isset($_POST['country'])){echo htmlentities($_POST['country']); } else { echo "Select Country *"; }?>
</option>
<?php foreach($countries as $country){ ?>
<option <?php echo ($_POST['country'] == $country->country_name ? 'selected="selected"':''); ?> value="<?php echo $country->country_name; ?>"><?php echo $country->country_name; ?>
</option>
<?php } ?>
</select>

Categories