简体   繁体   中英

PHP select option using value from MySQL

with this code I get dropdown menu to select:

<select name='select'>
$sql = mysql_query("SELECT sport FROM kategorija");
mysql_close();
while ($result = mysql_fetch_array($sql)) {
     <OPTION selected='{$kategorija}' VALUE='" . $result[0] . "'>" . $result[0] . "</OPTION>
}
 </select></td>

This is how my table looks:

ID DropDownMenu xxx yyy zzz

How to set that dropdown menu selected value is the value connected to that ID. In my case I always get last value from dropdown menu as selected one.

Try this: UPDATED

$out = '<select name="select">';

$sql = mysql_query("SELECT sport FROM kategorija");
mysql_close();

while ($result = mysql_fetch_assoc($sql)) {
    $out .= "<OPTION selected='" .$result['$kategorija']. "' VALUE='" .$result[0]. "'";
    if ($result['$kategorija'] == 'something') {
        $out .= "selected";
    }
    $out .= ">" .$result[0]. "</OPTION>";
}

$out .= "</select></td>";

echo $out;

first store the selected sport in database to a variable

eg:

$sport='cricket';//substitute with database fetch value
Sport: <select name="sport" >
<option value="All" >All</option>
<?php  $a="select * FROM kategorija";
        $d2=mysql_query($a); 

         while($d4=mysql_fetch_array($d2))
  {?>  <option value="<?php  echo $d4['sport']; ?>"<?php if($sport==$d4['sport']){ echo "selected";} ?> > <?php  echo $d4['sport']; ?> </option> <?php
      }
        ?></select>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM