-1

I currently have an HTML form where the options for a certain drop-down menu are hard-coded. Instead, I want to use PHP to...

  1. Look up the values in a column (cities) in a MySQL table (locations)
  2. Make those values the only options in the dropdown menu.

Any ideas how I would do this? This is what I have so far.

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

?>

....Omitted a bunch of HTML here....

<label for="city">What is your destination city?</label>
      <select class="form-control" id="city" name ="city" /><br />
          <option value="$data">$data</option>
      </select>
Trey
  • 201
  • 3
  • 14
  • http://stackoverflow.com/questions/8022353/how-to-populate-html-dropdown-list-with-values-from-database – Zentoaku Aug 20 '14 at 14:19

1 Answers1

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>
Legionar
  • 7,472
  • 2
  • 41
  • 70
  • Thanks for the quick response. I tried this out and I'm still seeing an error (dropdown menu is blank). I've tried running the MySQL query independent of the script, so I know that's working. Any troubleshooting suggestions? – Trey Aug 21 '14 at 14:16