从数据库填充的下拉列表的显示值(SQL Server)

时间:2015-08-31 07:54:17

标签: php sql-server drop-down-menu

我正在尝试显示从数据库填充的动态下拉列表的已保存值。我的代码如下:

<?PHP
$server = "xxx";
$options = array(  "UID" => "xxx",  "PWD" => "xxx",  "Database" => "xxx");
$conn = sqlsrv_connect($server, $options);
if ($conn === false) die("<pre>".print_r(sqlsrv_errors(), true));
echo " ";

$myquery="SELECT Department FROM Change_Details WHERE id='2137'";   
$fetched=sqlsrv_query($conn,$myquery) ; 
if( $fetched === false ) { die( print_r( sqlsrv_errors(), true ));}
    while($res=sqlsrv_fetch_array($fetched,SQLSRV_FETCH_ASSOC))
    {
        $Department=$res['Department'];
    }
 ?>

<div class="container"> <!-- Department -->
    <div class="form-inline clearfix">
        <label class="col-md-5">Department initiating the Request</label>
            <label name="Department"></label>
                <div class="col-md-5">
                            <?PHP
                            echo "<select name= 'Department' class='form-control selectpicker' onChange='getState(this.value)' Required>";
                            echo '<option value="$Department">'.'--Please Select Department--'.'</option>';
                            $sql = "SELECT ID,Name FROM Departments";
                            $query = sqlsrv_query($conn,$sql);
                            $query_display = sqlsrv_query($conn,$sql);
                            while($row=sqlsrv_fetch_array($query_display,SQLSRV_FETCH_ASSOC)){
                            echo "<option value='". $row['Name']."'>".$row['Name']. '</option>';
                            }
                            echo "</select>";
                        ?>
                </div>
    </div>
</div><br/>

工作原理:下拉列表正在完美填充,值也会保存到数据库中。

我需要:想要显示数据库中的已保存值和下拉列表,以便用户再次编辑该字段。感谢任何帮助:)

1 个答案:

答案 0 :(得分:1)

您需要获取当前用户选择的值,然后在迭代结果集时,您可以执行以下操作:

while($row=sqlsrv_fetch_array($query_display,SQLSRV_FETCH_ASSOC)){
    if ($Department == $row['Name']) {
        echo "<option selected='selected' value='". $row['Name']."'>".$row['Name']. '</option>';
        continue;
    }

    echo "<option value='". $row['Name']."'>".$row['Name']. '</option>';
}