简体   繁体   中英

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>

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.

<?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>";
?>

尝试使用switch case,并将值从数据库中放入switch,然后如果case值匹配,则将selected ='selected'设置selected ='selected'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM