user2519032 user2519032 - 7 months ago 37
SQL Question

Print selected attribute on select option with PHP and MySQL

I'm printing a select list from my database.

Here's a part of my code:

<form action="" method="post">
<div class="form-item">
<select name="specialties">
<?php
$query = "SELECT * FROM specialties";
$result = mysqli_query($connection, $query);

echo '<option value="All">' . $filterTitle . '</option>';
while($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$title = $row['title_'. $lang];

if($_POST['specialties'] == $id) {
$selected = 'selected';
}

echo '<option value="' . $id . ' "' . $selected . '>' . $title . '</option>';
}
?>
</select>
</div>

<div class="form-item">
<input class="form-submit" type="submit" name="submit" value="<?php echo $filterSubmit; ?>">
</div>
</form>


In this form when I choose some of the options, it filters the content. That's working properly and I don't need to post that part of the code.

First when I choose some option from the select list and after submit, it filter the content, but the select option shows the All value, instead of the selected option. After that I've tried with the code above and now when I submit the form, the select value shows the last option and all the options has
selected
attribute.

How can I change that logic, so when I select let's say the second option, after submitting the form, the
selected
attribute will appear only on the second option, so the text will be the second option?

CONCLUSION:
Thank you guys for your answers. You're all correct. I gave you all +1 and I choose the Hassaan's answer, because it's very well explained.

Answer

Currently you are checking/comparing values and generating variable. You need to use else condition because you must change/reset the value of generated variable. See the example below.

if($_POST['specialties'] == $id) {
    $selected = 'selected';
}
else
    $selected = '';