Default option selected from SQL query in drop-down list - php

I want to have a drop-down list have a default value akin to how you would have value="abc" in a text field or similar. The only caveat is that I would like it to be defaulted to where an SQL query points it to. Excuse the long code.
//prior code where table and `foreach()` loop begins
<td>
<input type="text"
value="<?php echo $var["author"]; ?>"
required="required">
</input>
</td>
<td>
<select name="condition"
value="<?php echo $var["condition"]; ?>"
<option>M</option>
<option>NM</option>
<option>E</option>
<option>G</option>
<option>P</option>
</select>
</td>
//subsequent code where table is closed
For the first half, I have a text field of default value $var["author"], because that is what I query before beforehand. For the second, I can't seem to get the same result, due to it being a drop-down menu instead of a text field. If the .sql query brings up "NM", the default value will be "M", always. Any way to do this?

What you want is this:
//prior code where table and `foreach()` loop begins
<td>
<input type="text"
value="<?php echo $var["author"]; ?>"
required="required">
</input>
</td>
<td>
<select name="condition">
<option value="M"<?php echo ($var["condition"] == 'M' ? ' selected="selected"' : ''); ?>>M</option>
<option value="NM"<?php echo ($var["condition"] == 'NM' ? ' selected="selected"' : ''); ?>NM</option>
<option value="E"<?php echo ($var["condition"] == 'E' ? ' selected="selected"' : ''); ?>E</option>
<option value="G"<?php echo ($var["condition"] == 'G' ? ' selected="selected"' : ''); ?>G</option>
<option value="P"<?php echo ($var["condition"] == 'P' ? ' selected="selected"' : ''); ?>P</option>
</select>
</td>
//subsequent code where table is closed
or more elegant:
$dropdownOptions = array('N', 'NM', 'E', 'G', 'P');
//prior code where table and `foreach()` loop begins
<td>
<input type="text"
value="<?php echo $var["author"]; ?>"
required="required">
</input>
</td>
<td>
<select name="condition">
<?php foreach ($dropdownOptions AS $option) {
echo '<option value="' . $option . '"' . ($var["condition"] == $option ? ' selected="selected"' : '') . '>' . $option . '</option>';
} ?>
</select>
</td>
//subsequent code where table is closed

Related

Pre-populating and compare select field with 'selected' option

I am pulling form data from home.php into results.php and using $_GET['xxxxx'] to pre-populate fields of another form. I can populate input fields okay, but how would you compare an option field and $sale_type to selected if equal?
home.php
<form action="results.php" method="GET">
<input id="address" name="address" type="text" class="form-control1"/>
<select type="text" name="sale_type" placeholder="Sale Type">
<option value="Sale">For Sale</option>
<option value="Rent">To Rent</option>
</select>
<input name="submit" type="SUBMIT" value="Next" class="form-control1">
</form>
results.php
Option fields are already populated to ensure the form will work if it's used without results from home.php. I need to compare $sale_type value with the option of name="sale_type and if equal change that option value to selected.
$address = $_GET['address'];
$sale_type = $_GET['sale_type']; ?>
<form method="POST">
<input id="address" name="address" type="text" value='<?php echo $address; ?>'>
<select type="text" name="sale_type" placeholder="Sale Type">
<option value="Sale">For Sale</option>
<option value="Rent">To Rent</option>
</select>
<button type="submit" id="filter">Search</button>
<input type="hidden" name="action" value="ek_search">
</form>
What I'd like results to do
$address = $_GET['address'];
$sale_type = $_GET['sale_type']; ?> //If value is Sale
<form method="POST">
<input id="address" name="address" type="text" value='<?php echo $address; ?>'>
<select type="text" name="sale_type" placeholder="Sale Type">
<option value="Sale" selected>For Sale</option> //Change to selected if equal
<option value="Rent">To Rent</option>
</select>
<button type="submit" id="filter">Search</button>
<input type="hidden" name="action" value="ek_search">
</form>
You could check and then marked as selected when condition satisfy. One of the example is :
<option value="Sale" <?php if(condition) echo "selected" ?> >For Sale</option>
You'd compare the variable to value in the option tag like so:
<option value="Sale" <?= ($sale_type === 'Sale') ? 'selected' : ''; ?>>For Sale</option>
Another, option, if you will, is to set an array of sale_types. Instead of checking each individual option value, you could loop through the options and check there. Like this:
$sale_types = [
'Sale' => 'For Sale',
'Rent' => 'To Rent',
'SomeOtherType' => 'Something Else'
];
Then in select element:
<? foreach ($sale_types as $sale_value => $sale_option): ?>
<option value="<?= $sale_option; ?>" <?= ($sale_type === $sale_option) ? 'selected' : ''; ?>><?= $sale_value; ?></option>
<? endforeach; ?>
If you're going to do very much of this at all, my recommendation is to build a PHP function. Otherwise, you end up with a bunch of mixed HTML / PHP to check conditions.
This allows you to set up and display a dropdown quickly any time you need to.
Something like this would do what you want and would be re-usable:
// Function to generate the HTML for a select
function dropdown_array( $name, $value, $array, $placeholder = '' ) {
$temp_input = '<select name="' . $name . '"';
$temp_input .= ( $placeholder ) ? ' placeholder="' . $placeholder . '"' : '';
$temp_input .= '>' . PHP_EOL;
if ( is_array( $array ) ) {
foreach ( $array as $val => $text ) {
$temp_input .= '<option value="' . $val . '"';
if ( $value === $val ) {
$temp_input .= ' selected';
}
$temp_input .= '>' . $text . '</option>' . PHP_EOL;
}
}
$temp_input .= '</select>' . PHP_EOL;
return $temp_input;
}
Then, in your situation, usage would look like so:
$array = array( 'Sale' => 'For Sale', 'Rent' => 'To Rent' );
echo dropdown_array( 'sale_type', $sale_type, $array, 'Sale Type' );

PHP keep dropdown value after submit

I have the following code for a simple calculator. The code works fine, but I want the value in the dropdown list to stay there after submitted. How would I do this?
Essentially, I want the operator to stay selected once the calculation has been done. At the moment, it just shows a '+', even if the sum is 25 / 5.
<?php
$number1 = $_POST['number1'];
$number2 = $_POST['number2'];
$operation = $_POST['operator'];
Switch ($operation) {
case 'add': $answer = $number1 + $number2;
break;
case 'minus': $answer = $number1 - $number2;
break;
case 'divide': $answer = $number1 / $number2;
break;
case 'multiply': $answer = $number1 * $number2;
break;
}
?>
<form name='calculator' method='post' action=''>
<table>
<tr>
<td>
<input name="number1" type="text" value="<?php i if(isset($_POST['number1'])) { echo htmlentities($_POST['number1']);}?>" />
</td>
<td>
<select name="operator">
<option value="add">+</option>
<option value="minus">-</option>
<option value="divide">/</option>
<option value="multiply">x</option>
</select>
</td>
<td>
<input name="number2" type="text" value="<?php if(isset($_POST['number2'])) { echo htmlentities($_POST['number2']);}?>" />
</td>
<td>
<input name="submit" type="submit" value="=" />
</td>
<td>
<input name="" type="text" value="<?php echo $answer ?>" />
</td>
</tr>
</table>
You have to set the selected attribute for the option that was submitted. So you have to check the submitted value for each option. In my solution I am using the ternary operator to echo the selected attribute only for the correct operator.
<select name="operator">
<option value="add" <?php echo (isset($_POST['operator']) && $_POST['operator'] == 'add') ? 'selected' : ''; ?>>+</option>
<option value="minus" <?php echo (isset($_POST['operator']) && $_POST['operator'] == 'minus') ? 'selected' : ''; ?>>-</option>
<option value="divide" <?php echo (isset($_POST['operator']) && $_POST['operator'] == 'divide') ? 'selected' : ''; ?>>/</option>
<option value="multiply" <?php echo (isset($_POST['operator']) && $_POST['operator'] == 'multiply') ? 'selected' : ''; ?>>x</option>
</select>
The code above is somewhat repetitive. It keeps repeating a lot of code and html. It would be great if we could factor out the repetitive stuff. Luckily we can do that by creating an array that stores the options and loop through them using a foreach, like this:
<?php
$options = [
'add' => '+',
'minus' => '-',
'divide' => '/',
'multiply' => 'x'
];
?>
<select name="operator">
<?php foreach ($options as $key => $label) { ?>
<option value="<?= $key ?>" <?= (isset($_POST['operator']) && $_POST['operator'] == $key) ? 'selected' : '' ?>><?= $label ?></option>
<?php } ?>
</select>

While filling in a form only update the form do not reload the whole page

I have got the following form:
<form action="" method="get" target="_self">
<select name="Category" class="dropmenu" id="Category"onchange="this.form.submit()">
<option value="">Any</option>
<option value="Keyboard"<?php if ($_GET['Category']=="Keyboard") {echo "selected='selected'"; } ?>>Keyboard</option>
<option value="Piano"<?php if ($_GET['Category']=="Piano") {echo "selected='selected'"; } ?>>Piano</option>
</select>
<select name='Manufacturer' class="dropmenu" onChange="this.form.submit()" >
<?php
echo '<option value="">Any</option>';
while ($row = mysql_fetch_array($RS_Search1)) {
$selected = $_GET['Manufacturer'] == $row['Manufacturer'] ? 'selected' : '';
echo '<option '.$selected.'>' . $row['Manufacturer'] . '</option>';
} ?> </select>
<select name="Color" class="dropmenu" onChange="this.form.submit()">
<?php
echo '<option value="">Any</option>';
while ($Color = mysql_fetch_array($RS_Search2)) {
$selected2 = $_GET['Color'] == $Color['Color'] ? 'selected' : '';
echo '<option '.$selected2.'>' . $Color['Color'] . '</option>';
} ?> </form>
Second form to submit
<form action="search2.php" method="get"> </select><input name="Category" type="hidden" value="<?php echo $_GET['Category']; ?>">
<input name="Manufacturer" type="hidden" value="<?php echo $_GET['Manufacturer']; ?>">
<input name="Color" type="hidden" value="<?php echo $_GET['Color']; ?>">
<select name="price" class="dropmenu">
<?php
echo '<option value="">Any</option>';
while ($Price = mysql_fetch_array($RS_Price)) {
$selected3 = $_GET['price_range'] == $Price['price_range'] ? 'selected' : '';
echo '<option '.$selected3.'>' . $Price['price_range']. '</option>';
} ?>
</select><input name="Search2" type="submit" id="Search2" value="Submit">
</form>
As you can see the option values are pulled from a db, after the first value is chosen. What the form does at the minute is reload the whole page. Is there a way to just reload the form in stead of reloading the whole page. I need to keep the values that are submitted on change of a option value to be able to fill in the next drop down menu.
Any help welcome.

How do I make html select box default to most recent db entry

I have an html select box that is populated by an array from the db. All the data in this table including the select box it written to a new table in the db along with current date. When the user returns to the class I want the select box to default to the last entry the user submitted whether it be the day before or a week before. I can get the query pretty close to where I need it but I dont really where to start as far as passing that to the select box.
Here is my select box that is echo from php.
<td>
<select name="movement[]" width=200>
<option>Select...</option>
<option>'. ($wc['mv_00']). '</option>
<option>'. ($wc['mv_01']). '</option>
<option>'. ($wc['mv_02']). '</option>
<option>'. ($wc['mv_03']). '</option>
<option>'. ($wc['mv_04']). '</option>
</select></td>
Here is the code for the entire array that is echo out.
if(empty($workout_class) === false)
{
foreach($workout_class as $wc){
if ($wc['pagenum'] !== $pagenum) continue 1;
echo '<tr>
<td><input type="hidden" name="client_id[]" value="'.($wc['client_id']).'">
<input type="hidden" name="first_name[]" value="'.($wc['first_name']).'">'. ($wc['first_name']).'
<span><input type="hidden" name="nickname[]" value="'.($wc['nickname']).'">('. ($wc['nickname']).')</span>
<span><input type="hidden" name="last_name[]" value="'.($wc['last_name']).'">'. ($wc['last_name']).'</span>
</td>
<td><input type="hidden" name="order[]" value="'.($wc['order']).'">'. ($wc['order']). '</td>
<td>
<select name="movement[]" width=200>
<option>Select...</option>
<option>'. ($wc['mv_00']). '</option>
<option>'. ($wc['mv_01']). '</option>
<option>'. ($wc['mv_02']). '</option>
<option>'. ($wc['mv_03']). '</option>
<option>'. ($wc['mv_04']). '</option>
</select></td>
<td><input type="hidden" name="rep_set_sec[]" value="'.($wc['rep_set_sec']).'">'. ($wc['rep_set_sec']). '</td>
<td><input type="hidden" name="rest[]" value="'.($wc['rest']).'">'. ($wc['rest']). '</td>
<td>00</td>
</tr>';
} // foreach($data_array
Can this be done with php or is this something where js would be better?
OK, here is my variable that get the last movement entered based on the class, client and order.
$recent_movement = recent_movement($class_id, $client_id, $order);
Here is my query that returns the array of movements from db based on MAX(date)
function recent_movement($class_id, $client_id, $order){
$class_id = (int)$class_id;
$client_id = (int)$client_id;
$query = mysql_query("SELECT `movement` FROM `completed_movements` WHERE `class_id` = '$class_id' AND `client_id` = '$client_id' AND `order` = '$order' AND
`date` = (SELECT MAX(`date`) FROM `completed_movements` WHERE `order` = '$order')");
$last_movement = mysql_fetch_array($query);
return $last_movement['movement'];
}
This is where Im not sure how to tell the select menu to set select="selected" based on what my $recent_movement returns.
if you had
<option>A</option>
<option>B</option>
<option>C</option>
When to pick "B" you would do
<option>A</option>
<option selected="selected">B</option>
<option>C</option>
As a result all you need to do is get the last value you wanted, and then for each output, if the value is the one you wanted add the "selected = ..." part.
(Edited to set value of selected to selected)
OK, for argument's sake, let's say that you store the latest selection in $recent_movement. Just compare the value of that variable to the value of the options, and set the matching option to "selected":
<?php
.
.
.
echo '...
<option' . ($ws['mv_00'] == $recent_movement ? ' selected="selected"' : "") . '>'. ($wc['mv_00']). '</option>
<option' . ($ws['mv_01'] == $recent_movement ? ' selected="selected"' : "") . '>'. ($wc['mv_01']). '</option>
<option' . ($ws['mv_02'] == $recent_movement ? ' selected="selected"' : "") . '>'. ($wc['mv_02']). '</option>
<option' . ($ws['mv_03'] == $recent_movement ? ' selected="selected"' : "") . '>'. ($wc['mv_03']). '</option>
<option' . ($ws['mv_04'] == $recent_movement ? ' selected="selected"' : "") . '>'. ($wc['mv_04']). '</option>
...';
You can also simplify this by implementing a loop with a counter:
<?php
$options = "";
for($i = 0; $i <= 4; $i++) {
$options .= '<option' . ($ws['mv_0' . $i] == $recent_movement ? ' selected="selected"' : "") . '>'. ($wc['mv_0' . $i]). '</option>';
}
UPDATE:
Had this been my own code, I would have made some minor changes. Instead of that huge echo, I would have just exited PHP mode and gone with straight HTML. I would have also used my looping string constructor (posted above) for the options:
<?php
foreach ($workout_class as $wc) :
if ($wc['pagenum'] !== $pagenum) continue 1;
$options = "";
for ($i = 0; $i <= 4; $i++) {
$options .= '<option' . ($ws['mv_0' . $i] == $recent_movement ? ' selected="selected"' : "") . '>' . ($wc['mv_0' . $i]) . '</option>';
}
?>
<tr>
<td><input type="hidden" name="client_id[]" value="<?= $wc['client_id'] ?>">
<input type="hidden" name="first_name[]" value="<?= $wc['first_name'] ?>"><?= $wc['first_name'] ?>
<span><input type="hidden" name="nickname[]" value="<?= $wc['nickname'] ?>">(<?= $wc['nickname'] ?>)</span>
<span><input type="hidden" name="last_name[]" value="<?= $wc['last_name'] ?>"><?= $wc['last_name'] ?></span>
</td>
<td><input type="hidden" name="order[]" value="<?= $wc['order'] ?>"><?= $wc['order'] ?></td>
<td>
<select name="movement[]" width=200>
<option>Select...</option>
<?= $options ?>
</select></td>
<td><input type="hidden" name="rep_set_sec[]" value="<?= $wc['rep_set_sec'] ?>"><?= $wc['rep_set_sec'] ?></td>
<td><input type="hidden" name="rest[]" value="<?= $wc['rest'] ?>"><?= $wc['rest'] ?></td>
<td>00</td>
</tr>
<?php endforeach; ?>
Ok. You split your echo where the tags are.
Then , you iterate through them and when you reach the one that you wish to set as default you simply set
<option selected="selected" value="value">Option</option>
In this way this option will be the default one when entering the page.
This will work in your case.
I do not recommend using echo to build your page. You should instead rely on a template engine in your application. I recommend Twig Template Engine .

How to preselect drop down choices and checkbox options in a form (PHP/MySQL)?

I am creating an update form where previously submitted information from a mysql database is grabbed to populate the current form. So this is what I have so far:
$select = mysql_query("SELECT * FROM some_table WHERE id = $id");
while ($return = mysql_fetch_assoc($select)) {
$name = $return['name'];
$bio = $return['bio'];
$maritalStatus = $return['marital_status'];
$favFood = $return['fav_food'];
}
<form action="page.php" method="post">
Name: <input type="text" name="name" value="<?php echo $name; ?>" /><br />
Bio: <textarea name="bio"><?php echo $bio; ?></textarea><br />
Marital Status
<select name="maritalStatus">
<option>Select One</option>
<option value="married">Married</option>
<option value="single">Single</option>
<option value="divorced">Divorced</option>
</select><br />
Favorite Food:
Cheeze: <input type="checkbox" name="favFood" value="cheeze" />
Cake: <input type="checkbox" name="favFood" value="cake" />
Oranges: <input type="checkbox" name="favFood" value="oranges" />
</form>
As you can see I am able to display data that was entered via an input text box or textarea just fine. But How to I have the "Marital Status" drop down preselected to the "divorced" option and the "Oranges" check box checked under "Favorite Food" GIVEN that those two choices are the ones that actually exist in the database?
Or, to avoid adding an if to each option, just do something like:
echo '<select name="maritalStatus">';
$status = array("Select one", "Married", "Single", "Divorced");
foreach($status as $s)
{
$sel = ($maritalStatus == $s) ? 'selected = "selected"' : '';
echo '<option value="'.$s.'" '.$sel.'>'.$s.'</option>';
}
echo '</select>';
EDIT:
To dynamically populate the select from the DB you could:
echo '<select name="maritalStatus">';
$res = mysql_query("SELECT status FROM marital_status");
while ($row = mysql_fetch_array($res))
{
$s = $row['status']
$sel = ($maritalStatus == $s) ? 'selected = "selected"' : '';
echo '<option value="'.$s.'" '.$sel.'>'.$s.'</option>';
}
echo '</select>';
<option value="single" <?php if($_REQUEST['maritalStatus'] == 'single'): ?>selected="selected"<?php endif ?>>Single</option>
And yes, you have to do an if for every option.
To preselect an option within in select you have to set the selected attribute like this:
<option value="married"<?= $marital_status == "married" ? ' selected="selected"' : ''?>>Married</option>
<option value="single"<?= $marital_status == "single" ? ' selected="selected"' : ''?>>Single</option>
<option value="divorced"<?= $marital_status == "divorced" ? ' selected="selected"' : ''?>>Divorced</option>
UPDATE
Or more DRY:
<?php foreach(array("married","single","divorced") as $status)): ?>
<option value="<?php= $status ?>"<?php $martial_status == $status ? ' selected="selected"' : '' ?>>
<?php= ucwords($status) ?>
</option>
<?php endforeach; ?>
Check Boxes
<input type="checkbox" id="id" name"checkbox" value="Option 1" checked>
or
<input type="checkbox" id="id" name"checkbox" value="Option 1" checked="checked">
Selection
<option value="Option 1" selected>Option 1</option>
or
<option value="Option 1" selected="selected">Option 1</option>
Conditional Selection
An example using jsp, where optionString is the variable to compare:
<input type="checkbox" id="id" name"checkbox" value="Option 1"
<%=(optionString.equalsIgnoreCase("Option 1"))? "checked":""%> />

Categories