数据驱动的下拉菜单

时间:2014-08-20 14:17:07

标签: php mysql

我目前有一个HTML表单,其中某个下拉菜单的选项是硬编码的。相反,我想使用PHP来...

  1. 在MySQL表(位置)的列(城市)中查找值
  2. 将这些值设为下拉菜单中的唯一选项。
  3. 我有什么想法会这样做?这是我到目前为止所做的。

    <?php
    
     //connect to the database
     $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
    
     //grab the city names from the MySQL table 
     $query = "SELECT cities FROM locations";
     $data = mysqli_query($dbc, $query);
    
     //close the db connection
     mysqli_close($dbc);
    
    ?>
    

    ....在这里省略了一堆HTML ....

    <label for="city">What is your destination city?</label>
          <select class="form-control" id="city" name ="city" /><br />
              <option value="$data">$data</option>
          </select>
    

1 个答案:

答案 0 :(得分:0)

<label for="city">What is your destination city?</label>
<select class="form-control" id="city" name="city">

<?php
  //connect to the database
  $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

  //grab the city names from the MySQL table 
  $query = "SELECT cities FROM locations";

  $res = mysqli_query($dbc, $query);

  while ($data = mysqli_fetch_assoc($res)) {
    echo '<option value="'.$data['cities'].'">'.$data['cities'].'</option>';
  }

  //close the db connection
  mysqli_close($dbc);
?>

</select>