Search code examples
phpsqlselectforeachselected

How to display values already selected in a select (PHP)


In need some help on this.

I have a form with a select who works perfectly and add all the values selected in my database. But now I want to do my update form, and I want that when I click to modify a user and arrive on the form, the values are already selected.

For example if in my first form, if I had selected the values 1 and 2, I would like 1 and 2 to be already selected when i go to the modification form. I've already did that :

<?php 

$nomLogiciel = getDemandeNomLogiciel($id_demande)[0];
$nom = explode(", ", $nomLogiciel);

foreach ($nom as $item) {
     $profilsTmp = getProfilByLogiciel($item); ?>

     <div class="form-floating mb-3">
       <select class="form-control selectpicker" id="id_profil" name="id_profil[]" multiple data-live-search="true">

         <?php foreach ($profilsTmp as $item2) { ?>
           <option value="<?php echo $item2['id_profil']; ?>"><?php echo $item2['profil']; ?></option>
         <?php } ?>

       </select>
       <label for="id_profil">Profil <?php echo $item ?></label>
     </div>
<?php } ?>

I already managed to do it with a simple select like this :

<select class="form-control selectpicker" id="nomPole" name="nomPole">
     <option value="Ambulatoire" <?php if ($one['pole'] == "Ambulatoire") { echo ' selected="selected"'; } ?>>Ambulatoire</option>
     <option value="Habitat et Vie Sociale" <?php if ($one['pole'] == "Habitat et Vie Sociale") { echo ' selected="selected"'; } ?>>Habitat et Vie Sociale</option>
</select>

But I would like to know how to do it with multiple values in a foreach ?

If you need my SQL function :

function getDemandeNomLogiciel($id_demande) {
    global $bd;
    $stmt = $bd->prepare('SELECT nom_logiciel FROM demandes WHERE id_demande = :id_demande');
    $stmt->bindParam(ID_DEMANDE, $id_demande);
    $stmt->execute();
    return $stmt->fetch();
}

function getProfilByLogiciel($nomLogiciel) {
    global $bd;
    $stmt = $bd->prepare('SELECT * FROM profils_logiciels WHERE nom_logiciel = :nomLogiciel');
    $stmt->bindParam(NOM_LOGICIEL, $nomLogiciel);
    $stmt->execute();
    return $stmt->fetchAll();
}

Thanks for your help !


Solution

  • I tried this and it worked very well. I just check if the values of my previous request can be found in the database. If yes I select them :

    <?php
    foreach ($structures as $item) { ?>
         <option value="<?php echo $item['id_structure']; ?>" 
         <?php if ($item['id_structure'] == $structurePrincipaleID['id_structure']) { echo ' selected="selected"'; } ?>>
         <?php echo $item['nom_structure'] ?></option>
    <?php } ?>