簡體   English   中英

如何在php中顯示數據庫中下拉列表的選定值

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

如何從我的mysql數據庫中顯示下拉列表的選定值。 下拉列表依賴於我的Category下拉列表。 這些是代碼:

<?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>";
    }   ?>

以下是填充“ Item Name下拉列表的第一個下拉列表( Category )的代碼。

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

當您列出下拉選項時,您可以檢查當前ItemID與傳遞的id值匹配。 如果匹配,則在其中拋出selected="selected" 嘗試:

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

編輯

我試圖清理一些代碼...不確定為什么你要使用do...while因為$row_Recordset1在第一次迭代時不可用。

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

你可以在里面使用這個代碼

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM