简体   繁体   中英

Selected item - Dropdown List - SQL

I have one dropdown list where I go to database to fill it :

<TH>
    <FORM>
        <p>Département</p>
        <SELECT size="1" id="depart" >
            <OPTION>
            <?php
                try {
                    // Parametres connexion
                    $bdd = new PDO('mysql:host=localhost;dbname=db', 'root', '') or die ("Impossible de se connecter au serveur où est stocké la Base de Données.");
                    // Requête
                    $resultats = $bdd -> query("SELECT DISTINCT Departement                                                                         FROM adresse                                                                                    ORDER BY Departement ASC");
                    // Tant qu'il y a des enregistrements, remplir la liste déroulante
                    while($d = $resultats->fetch()) 
                    {
                        echo '<option value="'.$d["Departement"].'">'.$d["Departement"].'</option><br/>';
                    }
                }
                catch(PDOException $e){
                    echo 'Erreur : ' . $e->getMessage();
                }
            ?>
            </OPTION>
        </SELECT>

        <!-- jQuery : Récupère le departement choisi -->
        <script>
            var departement_ = '';
            $('#departement').change(function departement() {departement_ = $('#departement option:selected').first().attr('value');

            // Display on input named "pu"
            // $('#pu').val(depart_);

            });
        </script>
    </FORM>
</TH>

As you can see, I retrieve the item selected in the dropdown list :

<TH>
    <FORM>
    <p>Commune</p>
    <SELECT size="1" id="commune" >
        <OPTION>
        <?php
            try {
                // Parametres connexion
                $bdd = new PDO('mysql:host=localhost;dbname=db', 'root', '') or die ("Impossible de se connecter au serveur où est stocké la Base de Données.");
                // Requête
                $resultats = $bdd -> query("SELECT DISTINCT Commune                                                                                 FROM adresse                                                                                    WHERE Departement='AVEYRON'                                                                                     ORDER BY Commune ASC");
                // Tant qu'il y a des enregistrements, remplir la liste déroulante
                while($d = $resultats->fetch()) 
                {
                    echo '<option value="'.$d["Commune"].'">'.$d["Commune"].'</option><br/>';
                }
            }
            catch(PDOException $e){
                echo 'Erreur : ' . $e->getMessage();
            }
            ?>
        </OPTION>
    </SELECT>

    <!-- jQuery : Récupère le code postal choisi -->
    <script>
    var commune_ = '';
    $('#commune').change(function commune() {
            commune_ = $('#commune option:selected').first().attr('value');

            // Display on input named "pu"
            // $('#pu').val(commune_);

            });
    </script>
</FORM>

As you can see one more time, I retrieve the item selected.

Let's me resume. The first list is here for choose a department for the user. For this, I execute a SQL request. Then, I retrieve the item selected. I put it in a var in jQuery (look my codes). And I want fill the second dropdown list in function of the item selected in the first dropdown, becasue for each department the list of "Code Postal (in France)" (or ZipCode for english) will be change.

Can you help me please ?

You can do that without ajax like in solution bellow, but you must execute both queries at same time, and do your logic in javascript, not to execute new sql query every time when you make change in select list.

If you have big number of results then it's better to use ajax than to load all data at once.

Few suggestions for rest of your code: * Don't use uppercase html tags * Don't connect multiple times to same mysql database in one file * Try to separate PHP, JavaScript and HTML/CSS code

<?php
try {
    // Parametres connexion
    $bdd = new PDO('mysql:host=localhost;dbname=db', 'root', '')
    or die ( "Impossible de se connecter au serveur où est stocké la Base de Données." );
    // Requête
    $resultats = $bdd->query("SELECT DISTINCT Commune,Departement   FROM adresse  ORDER BY Commune ASC");
    // Tant qu'il y a des enregistrements, remplir la liste déroulante
    $select_commune = '';
    while ($d = $resultats->fetch()) {
        $select_commune .= '<option data-department="' . $d["Departement"] . '" value="' . $d["Commune"] . '">' . $d["Commune"] . '</option>';
    }

    $resultats = $bdd->query("SELECT DISTINCT Departement   FROM adresse ORDER BY Departement ASC");
    // Tant qu'il y a des enregistrements, remplir la liste déroulante
    $select_depart = '';
    while ($d = $resultats->fetch()) {
        $select_depart .= '<option value="' . $d["Departement"] . '">' . $d["Departement"] . '</option><br/>';
    }
} catch (PDOException $e) {
    echo 'Erreur : ' . $e->getMessage();
}
?>
<th>
    <p>Département</p>
    <select size="1" id="departement">
        <option value="">Choose department</option>
        <?= $select_depart ?>
    </select>
</th>
<th>
    <p>Commune</p>
    <select size="1" id="commune">
        <option value="">Choose Commune</option>
        <?= $select_commune ?>
    </select>
</th>

<script>
    $(function () {
        $('#commune option').hide();
        var departement_ = '';
        $('#departement').change(function departement() {
            $('#commune option').hide();
            $('#commune option').first().show();
            departement_ = $('#departement option:selected').first().attr('value');
            $('#commune option[data-department="' + departement_ + '"]').show();
            // Display on input named "pu"
            // $('#pu').val(depart_);
        });
        var commune_ = '';
        $('#commune').change(function commune() {
            commune_ = $('#commune option:selected').first().attr('value');

            // Display on input named "pu"
            // $('#pu').val(commune_);
        });
    });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM