如何从数据库中获取的数组中回显选定的值

我想从数据库中回显选定的值以更新它然后存储它


例如,我有一个包含其他类别的printers表category中的类别的资产,当我想在edit页面上编辑此资产时,我应该得到一个包含所有类别的下拉列表,printers然后选择它,然后如果我想更改它,我会如果不离开不变


该数组是从表category内下拉,user_asset通过asset_category作为外键与数据库中的表连接


这是我到目前为止所做的


<label for="basicinput">الصنف : </label>

<?php 

    $result = mysqli_query($conn, "SELECT * FROM category");

?>

<select name="asset_category" class="form-control" required>

    <?php while( $row = mysqli_fetch_array($result)) {?>

    <option value="<?php echo $row['category_id'];?>">

        <?php echo $row['cate_name'];?>

    </option>

    <?php }?>

</select>

</div>


www说
浏览 177回答 2
2回答

侃侃无极

您可以添加 if 检查if ($row['cate_name'] == 'computer') { ?>,然后添加selected到此选项:<label&nbsp; for="basicinput">الصنف : </label><?php&nbsp; &nbsp; $result = mysqli_query($conn, "SELECT * FROM category");?><select name="asset_category" class="form-control"&nbsp; required ><?php while( $row = mysqli_fetch_array($result)) {&nbsp; &nbsp; if ($row['cate_name'] == 'computer') { ?>&nbsp; &nbsp; &nbsp; &nbsp; <option value="<?php echo $row['category_id'];?>" selected><?php echo $row['cate_name'];?></option>&nbsp; &nbsp; <?php } else { ?>&nbsp; &nbsp; &nbsp; &nbsp; <option value="<?php echo $row['category_id'];?>"><?php echo $row['cate_name'];?></option>&nbsp; &nbsp; <?php }}?></select>注意:如果您有多个属于该类别的元素,它将选择最后一个。

温温酱

答案很简单..让我们把这段代码<label for="basicinput">الصنف : </label><?php&nbsp;&nbsp; &nbsp; $result = mysqli_query($conn, "SELECT * FROM category");?><select name="asset_category" class="form-control" required>&nbsp; &nbsp; <?php while( $row = mysqli_fetch_array($result)) {&nbsp; if($row['cate_name']== printers)&nbsp; { ?>&nbsp; &nbsp; <option value="<?php echo $row['category_id'];?>" selected="selected">&nbsp; &nbsp; &nbsp; &nbsp; <?php echo $row['cate_name'];?>&nbsp; </option>&nbsp;<?php } else { ?>&nbsp; &nbsp; <option value="<?php echo $row['category_id'];?>">&nbsp; &nbsp; &nbsp; &nbsp; <?php echo $row['cate_name'];?> </option>&nbsp; &nbsp; <?php }?></select></div>逻辑是使用while循环,使用if类检查条件,并在满足时将其设为选中。然后它将作为选定的值回显。
打开App,查看更多内容
随时随地看视频慕课网APP