开发者

optgroup for select field - both group and option fields in same table. How can I do this?

开发者 https://www.devze.com 2023-03-12 04:47 出处:网络
I have a search form that searches a table in my database. The table has the following columns: icao - name - country

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

icao - name - country

I have the php that will place these fields in select 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 the php is as follows:

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

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

I've tried this:

<?p开发者_StackOverflow社区hp
foreach ($airports as $airport)
{
echo '<optgroup label="'.$airport->country.'">';
echo '<option value="'.$airport->icao.'">'.$airport->icao.' - '.$airport->name.'</option>';
?>
<?php echo '</optgroup>';}?>

But it just creates an optgroup for every airport.

Any help on this would very much be appreciated, and thanks in advance.

Stuart


First of all, modify the query to sort by country first, then icao.

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

Then try this:

$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: To avoid XSS vulnerabilities in your code, you really should wrap all dynamic parts of the HTML you're building in htmlspecialchars() or some similar function.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号