如何在下拉列表中设置所选选项

时间:2017-05-04 00:39:36

标签: php if-statement html-select default selected

这将回显来自数据库的下拉值

<select name="PACKAGE_ID" id="PACKAGE_ID" ng-model="FormData.Phases" class="form-control" required>

<?php 
$result=mysqli_query($conn, "select * from unifi WHERE STATUS!='DELETE' ORDER BY PACKAGE_NAME ASC");
while ($row=mysqli_fetch_assoc($result)) {
?>
    <option name="UNIFI" value="<?php echo $row["PACKAGE_NAME"]; ?>">
        <?php echo $row[ "PACKAGE_NAME"]; ?>
    </option>
<?php } ?>

<?php $result=mysqli_query($conn, "select * from streamyx WHERE STATUS!='DELETE' ORDER BY PACKAGE_NAME ASC");
while ($row=mysqli_fetch_assoc($result)) {?>
    <option name="STREAMYX" value="<?php echo $row["PACKAGE_NAME"]; ?>">
        <?php echo $row[ "PACKAGE_NAME"]; ?>
    </option>
<?php } ?>


<?php $result=mysqli_query($conn, "select * from webe WHERE STATUS!='DELETE' ORDER BY PACKAGE_NAME ASC");
while ($row=mysqli_fetch_assoc($result)) {?>
    <option name="WEBE" value="<?php echo $row["PACKAGE_NAME"]; ?>">
        <?php echo $row[ "PACKAGE_NAME"]; ?>
    </option>
<?php } ?>

<?php $result=mysqli_query($conn, "select * from dome WHERE STATUS!='DELETE' ORDER BY PACKAGE_NAME ASC");
while ($row=mysqli_fetch_assoc($result)) {?>
    <option name="WEBE" value="<?php echo $row["PACKAGE_NAME"]; ?>">
        <?php echo $row[ "PACKAGE_NAME"]; ?>
    </option>
<?php } ?>

下面是如何根据故障单ID

从数据库中获取值
 $sql = "SELECT * FROM cusinfo WHERE TICKET_ID = '".$strid."' ";
 $query = mysqli_query($conn,$sql);
 $result=mysqli_fetch_array($query,MYSQLI_ASSOC);

我希望回显例如。<<< $result["PACKAGE_ID"]==$row[ "PACKAGE_NAME"] echo selected >>

的选定值

1 个答案:

答案 0 :(得分:1)

由于您在后续查询中多次使用$result变量,因此您需要将$result["PACKAGE_CATEGORY"]保留为新变量,如下所示:

$selected=$result["PACKAGE_CATEGORY"];

您可以编写如下的内联条件语句:

echo "<option name=\"WEBE\" value=\"{$row["PACKAGE_NAME"]}\"",($row[ "PACKAGE_NAME"]==$selected?" selected":""),">{$row["PACKAGE_NAME"]}</option>";

这意味着如果条件为真,则将回显selected,如果为false,则将回显空字符串。

多行上的相同技术如下所示:

echo "<option name=\"WEBE\" value=\"{$row["PACKAGE_NAME"]}\"";
    echo $row["PACKAGE_NAME"]==$selected?" selected":"";
echo ">{$row["PACKAGE_NAME"]}</option>";

如果您不想使用内联条件,则标准语法为:

echo "<option name=\"WEBE\" value=\"{$row["PACKAGE_NAME"]}\"";
    if($row["PACKAGE_NAME"]==$selected){
        echo " selected";
    }
echo ">{$row["PACKAGE_NAME"]}</option>";