How to Store Date from Select HTML Tag to MySQL

Storing a date from <select> HTML tag to MySQL database is not that easy. I spent three hours to find out how. First time I tried to, I was thinking that my script was not effective. But, after reading some tutorial I found my own way to do it. Here it is.

MySQL script

Put this script at the top of your PHP file because it needs to store data first and then execute the script after.

<?php
if(isset($_POST['submit'])):
  $thedate=$_POST['dateyear']."-".$_POST['datemonth']."-".$_POST['dateday'];
  mysql_query("insert into income values('','".$thedate."')");
endif;
?>


HTML and PHP script

 

I managed to use for and foreach PHP functions to reduce ineffective repetition task of writing¬†<option value=”1″>Jan</option> and so on. So, the whole scripts became.


<select type="select" name="dateday" />
      <?php
      for($datei=1;$datei<=31;$datei++){
          echo '<option value="'.$datei.'">'.$datei.'</option>';
      }
      ?>
    </select>

    <!-- DATE MONTH -->
    <select type="select" name="datemonth" />
      <?php
        $montharray=array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
        $monthnum=0;
        foreach($montharray as $key){
          $monthnum++;
          echo '<option value="'.$monthnum.'">'.$key.'</option>';
        }
      ?>
    </select>

     <!-- DATE YEAR -->
    <select type="select" name="dateyear" />
      <?php
        for($datei=2011;$datei<=2030;$datei++){
          echo '<option value="'.$datei.'">'.$datei.'</option>';
        }
      ?>

I knew this way of programming is very vurnerable to injection, especial MySQL injection, it is the experts job to fix it. I believe this is the easiest way to learn about storing date information to MySQL database.

Oh yeah, don’t forget to set your date type in your MySQL database to DATE. The reason I don’t use VARCHAR type because it will be easier for MySQL database itself to search or sort query based on latest date or first time date.

Leave a Reply