1

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>
2
  • 1
    Please stop writing new code with the ancient mysql_* functions. They are no longer maintained and community has begun the deprecation process . Instead you should learn about prepared statements and use either PDO or MySQLi. If you care to learn, here is a quite good PDO-related tutorial. Commented Apr 29, 2012 at 11:56
  • Show an example of the output you're getting, and of the output you want. Commented May 3, 2012 at 12:27

2 Answers 2

2

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 ".

Sign up to request clarification or add additional context in comments.

Comments

1

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>';
}

1 Comment

You should not just have selected though. It should be <option value="whatever" selected="selected">something</option>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.