PHP-How to Display Current Selected Value in Form field - php

hi i have set up a php based form submission method for sorting rows per page in a select drop down menu, it is working fine i get to sort the rows according to value selected, but my problem is when a value is selected for sort it doesn't shows up in form selected field as whats currently selected.
what i mean to say is that when a value is selected in drop down menu for sorting rows it should show up as current in select-box as default value, and if nothing is selected then default row value should show up as current.
please see here here at the sorting method, it shows current(10) as default rows and when a value is selected it becomes as current on page reloads after querying database.
here is my html code for form field:
<form action="is-test.php" method="get">
<select name="rpp" onchange="this.form.submit()">
<option selected value="">show</option><!-- i want default & current selected value here -->
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
</select>
</form>
and php code for this sorting is:
$rowsperpage = '';
if (isset($_GET['rpp'])&& is_numeric($_GET['rpp'])) {
$rowsperpage = (int) mysql_real_escape_string($_GET['rpp']);
}else{
$rowsperpage='5';
}
and mysql query for this is:
$sql2 = "SELECT * FROM $tablename ORDER BY $orderby $sortby LIMIT $rowsperpage OFFSET $offset";
please sugest me a way to set selected value as current value.
Thanks

In your <option> tags, you should performed checking like this:
<option value="10" <?php if ($rowsperpage == 10) echo 'selected="selected"' ?>>10</option>
<option value="20" <?php if ($rowsperpage == 20) echo 'selected="selected"' ?>>20</option>
<option value="30" <?php if ($rowsperpage == 30) echo 'selected="selected"' ?>>30</option>
So if you select 20, it will displayed as the current value of the <select>
<option value="10">10</option>
<option value="20" selected="selected">20</option>
<option value="30">30</option>
To make things simpler, just use for loop like this:
for ($i = 10; $i <= 30; $i+= 10) {
echo "<option value=\"$i\" ".($rowsperpage == $i ? 'selected="selected"' : '').">$i</option>";
}

<option selected value="<?php echo $rowsperpage; ?>"><?php echo $rowsperpage; ?></option>
A possibly better way to do this is with a loop:
for ($i = 10, $i <= 30; $i +=10) {
$selected = ($i == $rowsperpage) ? ' selected="selected"' : '';
echo sprintf('<option value="%d"%s>%d</option>', $i, $selected, $i);
}

Related

When i select value form dropdwon is does not show in php $_Post['name']?

First of all, I am working on editing mode. I Fetch data from database then match it form selected item from last time.
when I change the value of dropdown it does not change it returns me the blank value in $_POST[]
I am populating a Drop Down Box using the following code.
<select name="agency_name" class="form-control">
<option value="">--Select--</option>
<?php
$query_agency= "Select * From `agency_name`";
$count = $db_handle->numRows($query_agency);
if($count != 0){
$i = 0;
$result_agency = $db_handle->runQuery($query_agency);
while($i != $count){
$agencyname = $result_agency[$i]['name'];
?>
<option value="<?php echo $result[0]['Agency_name'] ?>"
<?php if($result[0]['Agency_name']=="$agencyname"){echo "selected";} ?>>
<?php echo $agencyname;?>
</option>
<?php
$i++;
}
}
?>
</select>
I want to show change value and store in the database. Now how can I get the selected option value using PHP because I want the selected value to perform a query in the database.

PHP If variable equals value in dropdown then add 'selected' attribute to option

I have a drop down menu that checks whether a user has already selected a value by checking database and if they have, I want to add a 'selected' attribute to that option so that when they edit their profile, that option is preselected by what they chose.
Heres an example of what I am trying to accomplish. It works for text inputs but I don't know how to do it with dropdown lists.
So if user selects 'Dog', it gets place in database and adds 'selected' as attribute
$animal = $mysqli->escape_string($_POST['animal']);
//PHP UPDATE database script -------->
<label>Animal</label></br>
<select name='animal' value='<?php if($animal == value){ /*Add selected attribute to option */ ?>'>
<option value="" disabled selected>Select One</option>
<option value="" disabled>----------------</option>
<option value="Dog">Dog</option>
<option value="Cat">Cat</option>
<option value="Bird">Bird</option>
</select>
Define an array of options
$animals = ['Dog', 'Cat', 'Bird'];
Then generate the list of options for the <select> from that array, checking the selected animal against each one. If it matches, then add the selected attribute.
<label>Animal</label></br>
<select name='animal'>
<!-- select the default if none of the options are selected -->
<option value="" disabled <?php if (!in_array($animal, $animals)) echo 'selected' ?>>
Select One
</option>
<option value="" disabled>----------------</option>
<?php foreach ($animals as $option) {
echo "<option ";
if ($animal == $option) {
echo 'selected';
}
echo ">$option</option>";
?>
</select>
value attributes aren't required for your <option> elements in this case, since you're using the same values for the option text. (If the value attribute is omitted, the option text will be used as the value.)
Try it like this:
$animal = $mysqli->escape_string($_POST['animal']);
//PHP UPDATE database script -------->
echo '<label>Animal</label></br>
<select name="animal">
<option value="" disabled>Select One</option>
<option value="" disabled>----------------</option>
<option value="Dog" ' . ($animal == 'Dog' ? 'selected' : '') . '>Dog</option>
<option value="Cat" ' . ($animal == 'Cat' ? 'selected' : '') . '>Cat</option>
<option value="Bird" ' . ($animal == 'Bird' ? 'selected' : '') . '>Bird</option>
</select>';

php losing field value in a dinamically generated field after server side validation

I have a form with a select option that depending on its value will generate a x amount of select fields. user select #2 in field 1, 2 new self generated select fields will be added to the form.
Belows for is the part of the form that generates dinamically the new select fields.
<?php
for ($i = 1; $i <= $num_of_selects; $i++) {
?>
<select class="form-control" name="test[option<?= $i ?>]">
<option value="1" <?php echo(($withErrors && $test->getoption1() == 1 ) ? 'selected' : ''); ?>>Test 1</option>
<option value="2" <?php echo(($withErrors && $test->getoption1() == 2 ) ? 'selected' : ''); ?>>Test 2</option>
<option value="3" <?php echo(($withErrors && $test->getoption1() == 3 ) ? 'selected' : ''); ?>>Test 3</option>
</select>
<?php } ?>
All good until server side validation, after refreshing the form all select values are equal to the first values.
The thing is that I cant remember how to dinamically change the $test->getoption1() , so in the newer select would become something like $test->getoption2(), $test->getoption3(), and so on...
With getoption1() I collect the select value that was set by the user for the first select. Basically what I need is to be able to change the 1 dinamically depending on $i as I do in:
name="test[option<?= $i ?>]"
it should look to something like
$test->getoption[$i]() == $i ;
You could create a string with the function names and use it in place of the function
If I understand your question correctly it would look like this:
<?php
for ($i = 1; $i <= $num_of_selects; $i++) {
$functionOptions = 'getoption' . $i;
?>
<select class="form-control" name="test[option<?= $i ?>]">
<option value="1" <?php echo(($withErrors && $test->$functionOptions() == $i ) ? 'selected' : ''); ?>>Test 1</option>
<option value="2" <?php echo(($withErrors && $test->$functionOptions() == $i ) ? 'selected' : ''); ?>>Test 2</option>
<option value="3" <?php echo(($withErrors && $test->$functionOptions() == $i ) ? 'selected' : ''); ?>>Test 3</option>
</select>
PHP offers a good amount of "Variable Functions" that seem really helpful in situations like this. In the above example PHP looks for a function that matches the string.
More here http://php.net/manual/en/functions.variable-functions.php
Another way to handle it is try create a function that handles the input like $test->selectOption($i) and that function could just handle it and return the 3 integers.

PHP: selected value in dropdown box

I am doing an dropdown box, where I have let's say we have "option1" and "option2", the dropbox selects(marks) the "option1" and then we select the "option2", I want it to mark the "option2" in the dropdown box, but it doesn't mark it.
I'm trying to avoid to do javascript on this one, so I wonder if I can do it only on PHP.
Advices? Thanks!
Edit.
Well the problem is that i dont know how many options i have before building the dropdown menu. I get an array generated from a table in a database and make the options based on that.
Code:
<select name="department">
<?php foreach(bloggModelControler::getDepartments($_SESSION['user']) as $tempDepartment){
if(strcmp($tempDepartment, $department) == 0){
$selected = ".selected='selected'.";
}else{
$selected = ".selected=''.";
}
$dropdown = "<option \"$selected\" value=\"$tempDepartment\">\"$tempDepartment\" Selected</option>";
echo $dropdown;
}?>
</select>
and $department:
<?php
if(isset($_POST['department'])){
$department = $_POST['department'];
}else{
$departments = bloggModelControler::getDepartments($_SESSION['user']);
$department = $departments[0];
}
?>
Updated answer based on updated question (included code)
Don't put the periods inside the text variables for 'selected'.
if(strcmp($tempDepartment, $department) == 0){
$selected = "selected='selected'";
}else{
$selected = "selected=''";
}
Previous answer
In your PHP code that generates the HTML for the Select box, you have to specify which option is selected.
For example:
<select name="selectbox">
<option <?php if ($_POST['selectbox'] == 'option1') echo 'selected="selected"';?>>option1</option>
<option <?php if ($_POST['selectbox'] == 'option2') echo 'selected="selected"';?>>option2</option>
</selected>
Alternate syntax:
<select name="selectbox">
<option <?= ($_POST['selectbox'] == 'option1')? 'selected="selected"' : '';?>>option1</option>
<option <?= ($_POST['selectbox'] == 'option2')? 'selected="selected"' : '';?>>option2</option>
</selected>

Elegant way to add "selected" into a dropdrown form using PHP

I have a form that looks like this:
$guests = 2; // Just for testing
$form = 'Guests<br /><select name="guests">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>';
But the list of guests can be up to 100, so I probably shouldn't do a check for which value is selected manually.
What would be a good way for me to make the selected value become the selected value when the user sees this form?
Thanks!
What I normally do with dynamic select menus is use a foreach loop over an array, and just check each item.
Something like:
$dropdownName = "guests"; //Name of dropdown
$defaultValue = "0"; //value to select if there isn't one already set
$items = array('name'=>'value', 'anotherName'=>'anothervalue'); //items, name=>value
echo '<select name="'.$dropdownName.'">'; //Start Select
$selectedItem = (isset($_POST[$dropdownName])?$_POST[$dropdownName]:$defaultValue); //If a value is set, use it, otherwise use the default
foreach ($items as $name=>$value) //build select
{
echo '<option value="'.$value.'"'.(($selectedItem == $value)?' selected="selected"':'').'>'.$name.'</option>';
}
echo '</select>';
$guests = 2; // Just for testing
$form = 'Guests<br /><select name="guests">';
for($i = 0; $i <= 100; $i++)
$form .= "<option value='$i'{$guest == $i ? ' selected=\'selected\'' : ''}>$i</option>";
$form .= '</select>';
EDIT: $i < 101 was pretty lame...
You can store the value this value in a hidden field and on document.ready(), you can assign the selected value of drop down top the value of hidden value.
A solution that works but may not be efficient for some users...

Categories