如何从我的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>";
} ?>
以下是填充Category
下拉列表的第一个下拉列表(Item Name
)的代码。
<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>
答案 0 :(得分:2)
当您列出下拉选项时,您可以检查当前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>
答案 1 :(得分:0)
你可以在
中使用这段代码$selected=$row["ItemID"]==$id ?'Selected':'';
echo "<option value=\"".$row["ItemID"]."\" {$selected} >".$row["Item_Name"]."</option>";;