Nadim Obeid
Nadim Obeid

Reputation: 103

fetching values from database and displaying selected value in dropdown list not working in php

I am trying to fetch values from my database and display the selected value in a dropdown list with other values. I have seen many questions here regarding this issue but none of them is working. Please Help!

<select name= "indication_name" id= "update_indication_id" class="form-control" required>
  <?php
      $sql = "SELECT id,description From indications";
      $result=mysqli_query($con,$sql);
      while($row=mysqli_fetch_array($result)){
          echo "<option selected='selected'>" . $row['id']." - ". $row['description'];
      }

   ?>
</select>

Upvotes: 0

Views: 18240

Answers (3)

Vijay
Vijay

Reputation: 1

Try using switch case and put the value in switch from the database and then set selected ='selected' if the case value matches.

Upvotes: 0

Prashant Kumar Singh
Prashant Kumar Singh

Reputation: 61

<?php 
$server="localhost";
$username="root";
$password="";
$link=@mysql_connect($server, $username, $password) or die ("Cannot connect to mysql server: ".@mysql_error());
$dbname = 'database_name';
@mysql_select_db($dbname, $link) or die ("Cannot connect to database: ".@mysql_error());

$query="SELECT id,description from indications";
$result = @mysql_query ($query);
echo "<select name=indication_name value=' '>";
while($drop=@mysql_fetch_array($result)){
echo "<option value=$drop[id]>$drop[description]</option>";
}
echo "</select>";
?>

Upvotes: 0

Marcelo43
Marcelo43

Reputation: 57

There are three main errors I can see:

  1. You're making every option selected like that.

  2. The options don't have a value.

  3. And the option tags should be closed.

So it would be like this:

<select name= "indication_name" id= "update_indication_id" class="form-control" required>
  <?php
      $sql = "SELECT id,description From indications";
      $result=mysqli_query($con,$sql);
      while($row=mysqli_fetch_array($result))
          echo "<option value='" . $row['id'] . "'>" . $row['description'] . "</option>";
   ?>
</select>

Another thing, that isn't an error, but I personally think is good, is having a "unselected" option:

<select name= "indication_name" id= "update_indication_id" class="form-control" required>
  <option selected="selected" value="">-- Select an option --</option>
  <?php
      $sql = "SELECT id,description From indications";
      $result=mysqli_query($con,$sql);
      while($row=mysqli_fetch_array($result))
          echo "<option value='" . $row['id'] . "'>" . $row['description'] . "</option>";
   ?>
</select>

The value of that option should be null, so that required applies to it.

Upvotes: 1

Related Questions