简体   繁体   中英

How to show selected value of dropdown list from database in php

How do I show the selected value of a dropdown list from my mysql database. The dropdown list is dependent to my Category dropdown list. These are the codes:

<?php $id = $_GET["id"];
if(!$pupcon){
    die(mysql_error());
}
mysql_select_db($database_pupcon, $pupcon);

$getDropdown2 = mysql_query("select * from tblitemname where CategoryID = $id");
    while($row = mysql_fetch_array($getDropdown2)){
        echo "<option value=\"".$row["ItemID"]."\">".$row["Item_Name"]."</option>";
    }   ?>

Here are the codes for the first dropdown list ( Category ) which populates the Item Name dropdown.

<select name="Category" id="Category" class="field select large" onChange="loadXMLDoc(this.value);">
                                <?php do {  ?>
                                <option value="<?php echo $row_Recordset1['CategoryID']?>"<?php if (!(strcmp($row_Recordset1['CategoryID'], $row_editRecordset['CategoryID']))) {echo "selected=\"selected\"";} ?>><?php echo $row_Recordset1['CategoryName']?></option>
                                <?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); $rows = mysql_num_rows($Recordset1); if($rows > 0) {
  mysql_data_seek($Recordset1, 0);
  $row_Recordset1 = mysql_fetch_assoc($Recordset1);}?>
                            </select>

While you're listing out the drop down options, you can check to see if the current ItemID matches the passed id value. If it matches, throw a selected="selected" in there. Try:

$selected = ($row['ItemID'] == $id);
echo "<option value=\"".$row["ItemID"]."\" ".($selected ? " selected=\"selected\"":"").">".$row["Item_Name"]."</option>";

EDIT

I tried to clean up the code some...not sure why you're using a do...while because $row_Recordset1 wouldn't be available on the first iteration.

<select name="Category" id="Category" class="field select large" onChange="loadXMLDoc(this.value);">
    <?php 
    while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)) {  
    ?>
    <option value="<?php echo $row_Recordset1['CategoryID']; ?>"<?php if (!(strcmp($row_Recordset1['CategoryID'], $row_editRecordset['CategoryID']))) { echo " selected=\"selected\""; } ?>>
    <?php echo $row_Recordset1['CategoryName']; ?>
    </option>
    <?php 
    }
    ?>
</select>

you can use this code inside while

$selected=$row["ItemID"]==$id ?'Selected':'';
echo "<option value=\"".$row["ItemID"]."\" {$selected} >".$row["Item_Name"]."</option>";;

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