Board index   FAQ   Search  
Register  Login
Board index php forum :: Database mySQL & php coding

How do i set selected item in a dropdown PHP MySQL

Codes here !

Moderators: macek, egami, gesf

How do i set selected item in a dropdown PHP MySQL

Postby osamaboshi » Sun Apr 29, 2012 2:07 am

I have Table (bus)
columns (bus_id)(bus_no)
I tried echo <select> multiple with multi selection , I tried the below code but its repeat the (bus_no)
please help me to echo all bus and selected some buses and echo "selected" beside selected buses

<form name="editstudent" method="get" action="testmulti.php">
<select name="numBus[]" multiple>
<?
$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>
osamaboshi
New php-forum User
New php-forum User
 
Posts: 1
Joined: Sun Apr 29, 2012 1:48 am

Re: How do i set selected item in a dropdown PHP MySQL

Postby minimihi » Sun Apr 29, 2012 9:56 am

With each while loop you receive one row to $rowBus (with each loop variable is overwritten with new value), so there is no need to use foreach loop.

In foreach loop you're taking current row index to $key and value to $value. Then compare current row 'bus_id' value to $value variable, which always return true, since they contain same value.
Why are you doing this? :?

Also, when you describe array index, always use quotes. So that PHP wouldn't search for defined constants to insert into index.
For short, use $rowBus['bus_no'] instead of $rowBus[bus_no]

Code: Select all
<?
$SelectOptionWithThisID 
= 7;
$selBus=mysql_query("SELECT * FROM najdsy_bus order by bus_id");
while(
$rowBus = mysql_fetch_array($selBus)){
    if ($rowBus['bus_id'] == $SelectOptionWithThisID){
        $SelectedBus="selected";
    } else {
        $SelectedBus="";
    }
    echo '<option value="'.$rowBus['bus_id'].'"'.$SelectedBus.'>'.$rowBus['bus_no'].' '.$SelectedBus.'</option>';
}
?>
User avatar
minimihi
New php-forum User
New php-forum User
 
Posts: 238
Joined: Sat Apr 14, 2012 11:57 am
Location: Vilnius, Lithuania


Return to mySQL & php coding

Who is online

Users browsing this forum: No registered users and 1 guest

Sponsored by Sitebuilder Web hosting and Traduzioni Italiano Rumeno and antispam for cPanel.

cron