Optgroup for the select field - both groups and option fields in one table. How can i do this?

I have a search form that searches for a table in my database. The table has the following columns:

icao - name - country

I have php that will put these fields in the selection options for each row with the following query:

 public function airportstuff() {
        $query = "SELECT icao, name, country
                FROM phpvms_airports
                ORDER BY icao";

        return DB::get_results($query);
    }

Then php looks like this:

 <?php foreach ($airports as $airport)
 {echo '<option value="'.$airport->icao.'">'.$airport->icao.' - '.$airport->name.'</option>';}
                    ?>

This works fine, but I want to be able to use the country column as an optgroup, so each country is an optgroup, with the corresponding airports for that country in the right optgroup.

I tried this:

<?php
foreach ($airports as $airport)
{
echo '<optgroup label="'.$airport->country.'">';
echo '<option value="'.$airport->icao.'">'.$airport->icao.' - '.$airport->name.'</option>';
?>
<?php echo '</optgroup>';}?>

But he just creates an optgroup for each airport.

Any help on this subject would be greatly appreciated, and thanks in advance.

Stewart

+3
source share
1 answer

, country, icao.

public function airportstuff() {
    $query = "SELECT icao, name, country
            FROM phpvms_airports
            ORDER BY country, icao";
    return DB::get_results($query);
}

:

$previousCountry = null;
foreach ($airports as $airport) {
    if ($previousCountry != $airport->country) {
        // close the previous optgroup tag only if this isn't our first time through the loop
        if ($previousCountry !== null) {
            echo '</optgroup>';
        }
        echo '<optgroup label="'.$airport->country.'">';
    }
    echo '<option value="'.$airport->icao.'">'.$airport->icao.' - '.$airport->name.'</option>';
    $previousCountry = $airport->country;
}
// close the final optgroup only if we went through the loop at least once
if ($previousCountry !== null) {
    echo '</optgroup>';
}

BTW: XSS , HTML, , htmlspecialchars() .

+5

All Articles