John
John

Reputation: 952

Return data from database as selected value in dropdown

I am trying to return data from my database into a dropdown.

Here is my dropdown without the return:

<div class="col-md-9 col-sm-9 col-xs-12">
  <select class="form-control select2" id="status" name="status" style="width: 100%;">
    <option value="1">Active</option>
    <option value="0">Inactive</option>
  </select>
</div>

The following statement returns an 1 or 0:

SELECT status FROM users WHERE id=1

In this case value 1 means Active and 0 means Inactive.

Does someone know how I can present the returned value as the selected value?

For textboxes I am using the following script:

<input type="text" class="form-control" id="name" name="name" required="required" value="<?php
  $servername = "localhost";
  $username = "root";
  $password = "";
  $dbname = "db";

  $conn = new mysqli($servername, $username, $password, $dbname);
  if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
  } 

  $sql = "SELECT name FROM users WHERE id='". $_GET['id'] ."';
  $result = $conn->query($sql);

  if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
      echo nl2br(htmlspecialchars($row["name"]));
    }
  } else {
  echo "";
  }
  $conn->close();
?>">

Edit 1:

I get an Error when I try this:

if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
    echo '<label class="control-label col-md-3 col-sm-3 col-xs-12">Status</label>';
    echo '<div class="col-md-9 col-sm-9 col-xs-12">';
    echo '<select class="form-control select2" id="geactiveerd" name="geactiveerd" style="width: 100%;">';
    echo '<option ($row["status"] == "1") ? "selected="selected"' : '"value="1">Active</option>';
    echo '<option ($row["status"] == "0") ? "selected="selected"' : '"value="0">Inactive</option>';
    echo '</select>';
    echo '</div>';
  }
} else {

Upvotes: 1

Views: 94

Answers (1)

Murad Hasan
Murad Hasan

Reputation: 9583

Only the while loop shows for the answer-

Avoide the HTML and PHP tag combination.

<?php 
while($row = $result->fetch_assoc()) {?>
    <label class="control-label col-md-3 col-sm-3 col-xs-12">Status</label>
    <div class="col-md-9 col-sm-9 col-xs-12">
    <select class="form-control select2" id="geactiveerd" name="geactiveerd" style="width: 100%;">
    <option <?php echo ($row["status"] == "1") ? 'selected="selected"' : '';?> value="1">Active</option>
    <option <?php echo ($row["status"] == "0") ? 'selected="selected"' : '';?> value="0">Inactive</option>
    </select>
    </div>
<?php }?>

Hope this will help you.

Upvotes: 1

Related Questions