user1364008
user1364008

Reputation: 9

How do i set selected item in a dropdown PHP MySQL

I have a table bus with columns bus_id, bus_no.

I tried echo multiple with multi selection, I tried the below code but its repeating the bus_no.

Please help me to echo all buses and echo selected beside the selected ones.

<form name="editstudent" method="get" action="testmulti.php">
<select name="numBus[]" multiple>

<?php
$selBus=mysql_query("SELECT * FROM najdsy_bus order by bus_id");
while ($rowBus=mysql_fetch_array($selBus)) {
    foreach ($numBus as $key=> $value) {
        if ($rowBus['bus_id']==$value) {
            $SelectedBus = "selected";
        } else {
            $SelectedBus = "";
        }
        echo '<option value="'.$rowBus['bus_id'].'"'.$SelectedBus.'>'.$rowBus['bus_no'].' '.$SelectedBus.'</option>';
    }
}
?>
</select>
<br/>
<input type="submit" value="test">
</form>

Upvotes: 1

Views: 1006

Answers (2)

Leri
Leri

Reputation: 12535

Replace $rowBus[bus_no] to $rowBus['bus_no'] and $rowBus[bus_id] to $rowBus['bus_id']

The reason of this changes is that $rowBus is an array with structure like this Array ([bus_id] => value). As you see its key is a string, so to access it you have to "tell" php to look for it.

The string can be represented in "some_string" or 'some_string'. Because key is some text without any special formatting for better performance you are recommended to use ' instead of ".

Upvotes: 2

Pavel Strakhov
Pavel Strakhov

Reputation: 40492

It seems that you shouldn't put echo '<option value="'... inside of foreach. Change it to this:

while ($rowBus=mysql_fetch_array($selBus)) {
  $SelectedBus="";
  foreach ($numBus as $key => $value){
    if ($rowBus["bus_id"]==$value){
      $SelectedBus="selected";
    }
  }
  echo '<option value="'.$rowBus["bus_id"].'"'.$SelectedBus.'>'
     .$rowBus["bus_no"].' '.$SelectedBus.'</option>';
}

Upvotes: 1

Related Questions