Jump to content

Data-Driven Dropdown


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
https://forums.phpfreaks.com/topic/290680-data-driven-dropdown/
Share on other sites

Your code looks fine and should be generating the <option></option> tags for each city in your locations table.

 

If no options are being generate you need to start debugging your PHP code to see where it failing. 

 

I'd start by checking mysql has not returned an error. Use mysqli_error to check.

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.