Reputation:
I have a drop down menu which lists the associated 'IDs' from the mysql database:
<fieldset>
<legend><strong>Change ID:</strong></legend>
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$databaseName = "change_management";
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
$query3 = "SELECT `change_id` FROM `change_request_tbl` WHERE (approval_disposition LIKE 'Requires Editing')";
$result3 = mysqli_query($connect,$query3);
?>
<select required name="change_id">
<option value="">Please specify...
<?php
while ($roww = mysqli_fetch_array($result3))
{
echo "<option value='".$roww['change_id']."'>".$roww['change_id']."</option>";
}
?>
</select>
<input type="submit" name="get" value="Get Details" class="btn">
</fieldset><br><br><br>
When the user clicks "Get Details" the dropdown reverts back to "Please specify". I have found many examples of how to save the value after submission, but none seem to be applicable to my code as I am fetching values from the database. Is there anyway to save the last inputted values in this current format?
Upvotes: 0
Views: 4467
Reputation: 219057
When the user submits the form, the form value change_id
has the value you're looking for. So when populating your option
elements you can check if any of them match what was submitted and set it to be selected. Something like this:
if (isset($_POST['change_id']) && $roww['change_id'] == $_POST['change_id']) {
echo "<option selected value='".$roww['change_id']."'>".$roww['change_id']."</option>";
} else {
echo "<option value='".$roww['change_id']."'>".$roww['change_id']."</option>";
}
Or if you want it all on one line (using the ternary conditional operator):
echo "<option ".((isset($_POST['change_id']) && $roww['change_id'] == $_POST['change_id']) ? "selected" : "")." value='".$roww['change_id']."'>".$roww['change_id']."</option>";
Upvotes: 1