keep selected select value

0

Hi, I have a select that filled it with values from the database; each value is associated with another table. What I need is that the option of select that appears selected is the one that is associated with the other table.

<?php
 require('connect.php');
 for ($i=0; $i < 3; $i++) {
  echo "<select name='in".($i+1)."'>";
  foreach ($mysqli->query('SELECT * FROM base1') as $b1) {
   $sel = false;
   foreach ($mysqli->query("SELECT * FROM base2 WHERE id='$id'") as $b2) {
    if ($b2['id']==$b1['id']) {
     $sel = true;
     break;
    }
   }
   echo "<option value='".$b1['id']."'>".$b1['dat']."</option>";
  }
 echo "</select><label>Dato ".($i+1)."</label>";
?>

I tried the variable sel keep it selected but only keeps me selected the last value associated with id .

An example of the most approximate of the scheme that I want to achieve is like a form of questions associated with a user; There are several questions but only one selected by the user and this must appear selected in select .

Thank you in advance for your collaboration.

    
asked by Johan Solano Contreras 29.11.2018 в 15:18
source

1 answer

0

One option could be that if $b2['id']==$b1['id'] you add the selected parameter to that <option> element, like this:

<?php
 require('connect.php');
 for ($i=0; $i < 3; $i++) {
  echo "<select name='in".($i+1)."'>";
  foreach ($mysqli->query('SELECT * FROM base1') as $b1) {
   foreach ($mysqli->query("SELECT * FROM base2 WHERE id='$id'") as $b2) {
    if ($b2['id']==$b1['id']) {
     echo "<option value='".$b1['id']."' selected>".$b1['dat']."</option>";
    }else{
     echo "<option value='".$b1['id']."'>".$b1['dat']."</option>";
   } 
  }
 echo "</select><label>Dato ".($i+1)."</label>";
?>
    
answered by 29.11.2018 в 16:43