Skip to content
Advertisement

Select Correct Value in Dropdown Box from Database with For Loop

I have a couple of dropdown boxes for Day and Year inputs. The values are taken during sign up so this dropdown is for updating purposes. I want to prepopulate the two dropdowns with the correct values that are stored in the database. The values in the dropdown are populated using a for loop and when the form is submitted the new updated value should be submitted.

Here are my two dropdowns and the PHP code to retrieve the day and year from the database:

        <?php
           $dateOfBirth = explode("/", $users[0]['date_of_birth']);
           $day = $dateOfBirth[0];
            $month = $dateOfBirth[1];
            $year = $dateOfBirth[2];

          ?>

   <div class="form-group col-md-3">
         <select id="day" name="day" class="form-control" required>
         <?php for( $i=1; $i <=31; $i++) { ?>
         <option  value="<?php echo $i; ?>"><?php echo $i; ?></option>
         <?php } ?>
         </select>
   </div>

   <div class="form-group col-md-3">
         <select id="year" name="year" class="form-control" required>
          <?php for( $i=1940; $i <=  date("Y") -18; $i++) { ?>
          <option value="<?php echo $i; ?>"><?php echo $i; ?></option>
           <?php } ?>
            </select>
   </div>

Any help is appreciated!

Advertisement

Answer

You didn’t check the value with loop data learn form this code

    <?php
           $dateOfBirth = explode("/", $users[0]['date_of_birth']);
           $day = $dateOfBirth[0];
            $month = $dateOfBirth[1];
            $year = $dateOfBirth[2];
          ?>
   <div class="form-group col-md-3">
         <select id="day" name="day" class="form-control" required>
         <?php for( $i=1; $i <=31; $i++) { 
         $selected_day = ($day == $i)?'selected="selected"':''; // Check the CODE here 
         ?>
         <option  value="<?php echo $i; ?>" <?=$selected_day; ?> ><?php echo $i; ?> 
        </option>
         <?php } ?>
         </select>
   </div>
   <div class="form-group col-md-3">
         <select id="year" name="year" class="form-control" required>
          <?php for( $i=1940; $i <=  date("Y") -18; $i++) { 
                $selected_year = ($year == $i)?'selected="selected"':'';  // Check the CODE here 
          ?>
          <option value="<?php echo $i; ?>" <?=$selected_year ?> ><?php echo $i; ?></option>
           <?php } ?>
            </select>
   </div>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement