Jump to content

Data-Driven Dropdown


thoward
Go to solution Solved by thoward,

Recommended Posts

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.

<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> 

Link to comment
Share on other sites

I agree with Ch0cu3r, the DB connection or query are likely failing - but you aren't checking for errors. I'd also suggest separating the "Logic" from the "Output". Makes debugging much easier.

 

Try this.

<?php
 
//connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
    die("Connect failed: " . mysqli_connect_error());
}
 
//grab the city names from the MySQL table 
$query = "SELECT cities FROM locations";
$result = mysqli_query($dbc, $query);
if(!$result)
{
    die("Query failed: " . mysqli_error($dbc)):
}
 
$cityOptions = '';
while ($row = mysqli_fetch_assoc($result))
{
    $cityOptions .= "<option value='{$row['cities']}'>{$data['cities']}</option>\n";
}
 
//close the db connection
mysqli_close($dbc);
 
?>
 
Select a city:
<select name="city">
<?php echo $cityOptions; ?>
</select>

 If you still get a blank select with no errors, then I'd guess that there are no values for 'cities' in the 'locations' table. But, you could check for that as well.

Edited by Psycho
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.