phpformsoptgroup

How to include the optgroup containing the chosen option when submitting a form?


<?php $kategorie = $pdo->prepare("SELECT kategorie FROM tdgm_kategorien");
        $kategorie->execute(array()); ?>
<select name="rubrik" id="where" class="input">
    <?php while($r = $kategorie->fetch()) { 
   $kat = $r['kategorie']; ?>
    <optgroup label="<?= htmlspecialchars($r['kategorie'], ENT_COMPAT, 'UTF-8') ?>" 
              value="<?= htmlspecialchars($r['kategorie'], ENT_COMPAT, 'UTF-8') ?>">
        <?php $rubrik = $pdo->prepare("SELECT rubrik FROM ".$r['kategorie']."");
        $rubrik->execute(array());?>
        <?php while($e = $rubrik->fetch()) { ?>
        <option class="option" value="<?= htmlspecialchars($e['rubrik'], ENT_COMPAT, 'UTF-8') ?>">
            <?= htmlspecialchars($e['rubrik'], ENT_COMPAT, 'UTF-8') ?> </option><?php } ?></optgroup><?php } ?>
</select>

How can I pass the corresponding value of an optgroup to a script according to the option chosen?


Solution

  • optgroup has no value attribute. But you can prepend the optgroup value to the option seperated by something like ::. Then on the server, you split the value by :: to get both the $kategorie and the $rubrik.

    HTML

    <?php 
        $kategorie = $pdo->prepare("SELECT kategorie FROM tdgm_kategorien");
        $kategorie->execute(array()); ?>
        <select name="rubrik" id="where" class="input">
            <?php while($r = $kategorie->fetch()) { 
                $kat = htmlspecialchars($r['kategorie'], ENT_COMPAT, 'UTF-8'); ?>
                <optgroup label="<?= $kat ?>">
                    <?php $rubrik = $pdo->prepare("SELECT rubrik FROM ".$r['kategorie']."");
                    $rubrik->execute(array());?>
    
                    <?php while($e = $rubrik->fetch()) {
                        $rub = htmlspecialchars($e['rubrik'], ENT_COMPAT, 'UTF-8') ?>
                        <option class="option" value="<?= $kat.'::'.$rub ?>"><?= $rub ?></option>
                    <?php } ?>
                </optgroup>
            <?php } ?>
        </select>
    ?>
    

    SERVER

    <?php
    
    $exp = explode('::', $_POST['rubrik'] ?? '');
    $kategorie = $exp[0] ?? '';
    $rubrik = $exp[1] ?? '';