Populate drop down form with months and year php

Pete Naylor picture Pete Naylor · Nov 17, 2014 · Viewed 13.5k times · Source

I am trying to create two drop downs with HTML and PHP. The first is an auto submit that sends a month to a session variable:

<form action="" method="post">
      <select name="month" onchange="this.form.submit()">
        <option value="">-- Select Month --</option>
        <?php $month = date('n'); // current month
         for ($x = 0; $x < 12; $x++) { ?>
          <option value="<?php echo date('m', mktime(0,0,0,$month + $x,1)); ?>" 
          <?php echo date('m', mktime(0,0,0,$month + $x,1)) == $_SESSION['month'] ? "selected='selected'":""; ?> >
          <?php echo date('F Y', mktime(0,0,0,$month + $x,1)); ?>
         <?php } ?>
      </select>
    </form>

This works great. But I then need a second drop down with the day name and number:

<form action="" method="post">
      <select name="day" onchange="this.form.submit()">
        <option value="">-- Select Day --</option>
        <?php for ($i = $current_day; $i < 31; $i++) { 
        $tmp_date = $_SESSION['year']."/".$_SESSION['month']."/".$i; 
              $weekday = date('D', strtotime($tmp_date));  { ?>
        <option value="<?php echo $i; ?>" <?php echo $i == $_SESSION['day'] ? "selected='selected'":""; ?> >
        <?php echo $weekday." ".$i; ?>
     <?php  } ?>  
     <?php } ?>
        </option>
        <?php } ?>
      </select>
    </form>

This uses a temp date with a session variable as '2014' which I set before. I need to remove the session year variable and get the first drop down to know which year the month selected is and then pass this to the temp date so that it populates the day name and number correctly for the next year (2015) if you choose January onwards. At the moment it only shows the day name and number from the current year (2014) in this case.

Answer

Pete Naylor picture Pete Naylor · Nov 18, 2014
<?php
if(isset($_POST)) {
    $date = explode('-', $_POST['month']);
    $year = $date[0];
    $month = $date[1];
    echo "Year: ".$year." Month: ".$month;
}
?>

<form action="" method="post">
<select name="month" onchange="this.form.submit()">
<?php
  for ($i = 0; $i <= 12; ++$i) {
    $time = strtotime(sprintf('+%d months', $i));
    $value = date('Y-m', $time);
    $label = date('F Y', $time);
    printf('<option value="%s">%s</option>', $value, $label);
  }
  ?>
</select>

This gives me the year and month as separate values.