user2519032 user2519032 - 1 year ago 169
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">
$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>';

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

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

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

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 Source

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';
    $selected = '';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download