More on Dates in PHP

I ran into quite a few blips when I tried to post some dates to the MySQL database. Very often,  I got all zeros input into the database. Then, it showed the wrong dates (1969 or something). The following code is what I arrived at after a lot a research, a call to my Mom for more research, and a bit of testing. I’m thrilled to finally have this working!

To start off with, your date must be in YYYY-MM-DD format. For me, that was simple. Just change the initial session variable.

 $_SESSION['tdate'] = Date("Y-m-d");
 //or for testing
 $_SESSION['tdate'] = "2012-09-12";
 $fv = array();

 //$fv (form values) array filled from $_POST data and validated //then //execute INSERT INTO with date
 $insert_vars = "Fname, Lname, `date-regis`";
 $insert_vals = "'" . $fv['fname'] . "', '" . $fv['lname'] . 
 ", '" . $fv['regdate'] . "'";

 $isql = "INSERT INTO " . $mydatabase .
 "(" . $insert_vars . ") " .
 "VALUES (" . $insert_vals . ")";

 $iresult = mysql_query($isql, $con);

 if(! $iresult )
  {
    die('Could not enter data: ' . mysql_error());
  }

 //lastly, I wanted to display the date a bit differently
 $datetodisplay = date("m/d/Y", strtotime($row['date-regis']));

A few things to note about the above code.

  1. I’ve learned to never use hyphens in MySQL column names a little too late. Thankfully, the back tick (`) helps keep me from having to reinvent the wheel (see the column `date-regis`).
  2. The date in YYYY-MM-DD format is insert into the database enclosed in single quotes (‘) just like a string.
  3. The last line of code there can be used to initialize your dates into the proper format for the databases, if need be.

As the title suggests, I’ve written on dates in PHP before. That post is all about comparing dates.

Leave a Reply