简体   繁体   中英

Creating a drop down list in php from database with unknown amount of values

I am creating a drop down list in php where each item from that column in the table is shown.

Once one option is picked then another drop down list occurs with the other values from that row where the first item was picked. In mine first they have to pick and time then after the time is picked that ids associated with that time is supposed to be in that drop down list however only the last value is the drop down list is saved in the session even if that one isn't picked for both the first and second dropdown list.

I don't understand why the value picked isn't the value stored:

 <?php
   $select = '<select name = "flytime" size = "1">';
    while ($row = mysql_fetch_array($rs))
    {

    $select.= '<option value="' .$row["ID"].'" >     '.$row['flytime'].' </option>';
     $_SESSION["flytime"] =  $row["flytime"]; 
    }

     $time = $_SESSION["flytime];

     $select.= '</select>';
      echo $select;
     echo $time;
     ?>
     <p><input type="submit"  value="submit" name ="submit" /></p>
      <?php 
      mysql_close($conn); ?>

      <?php
      $conn = mysql_connect("localhost");
      mysql_select_db("hello", $conn)
      or die ('Database not found ' . mysql_error() );
      $sql = "SELECT * FROM fly WHERE flytime = '".$flytime ."';";
      $rs = mysql_query($sql, $conn)
      or die ('Problem with query' . mysql_error());
       ?>

      <?php

      if(isset($_POST["submit"]))
         {
        $select = '<select name = "ID" size = "1">';
        while ($row = mysql_fetch_array($rs))
         {

        $select.= '<option value="' .$row["flytime"].'" >  '.$row['ID'].' </option>';
        $_SESSION["ID"] =  $row["ID"] ; 
         }

       $select.= '</select>';
       echo $select;
       }
       ?>

you can only see the last values from your selects stored in your session variables, because you are overwriting the values of your session variables in your loops:

while ($row = mysql_fetch_array($rs))
{
    /* ... */
    $_SESSION["flytime"] =  $row["flytime"]; 
}

in the example above you are constantly using the same variable to save the value of $row["flytime"] . the variable only holds one value, that's why you only save the last value appearing in your loop.

solution tips:
to save a value to a PHP session variable dynamically from a select, take a look into AJAX (maybe in combination with jQuery ).
PHP doesn't have dynamic client-side behavior like that - once the page is rendered, PHP's job is done until you load the next page or use an AJAX request.

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