如何在php中显示数据库中下拉列表的选定值

时间:2012-05-10 11:18:36

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

以下是填充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>

2 个答案:

答案 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>";;