SR1092
SR1092

Reputation: 565

Display value for dropdown populated from database (SQL Server)

I am trying to display the saved value for a dynamic dropdown that is populated from a database. My code is as below :

<?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/>

What is working : The dropdown is being populated perfectly, and the value is also saved into the database.

What I need : Want to display the saved value from the database and the dropdown as well for the user to edit that field again. Appreciate any help :)

Upvotes: 2

Views: 1879

Answers (1)

Gori
Gori

Reputation: 361

You need to get the current user selected value, then when iterating over the result set you can do something like this:

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>';
}

Upvotes: 1

Related Questions