Thursday, October 19, 2006

MySQL DATE fields and PHP

The MySQL DATE field format is YYYY-MM-DD. So let's suppose you have a date in a text format and want to write the date to a field in MySQL database. Here are the steps: Use the PHP strtotime() function to create a timestamp:
$mydate = strtotime('31 Jan 2006');
Use the date() function to reformat the date in MySQL format:
$mydate = date('Ymd', $mydate);
Write the date (along with anything else) to the database. Note the formatting of the query in that the date value can be treated as 'text':
$sql = "INSERT INTO database.table ";
$sql .= "(adate) VALUES('".$mydate."')";
mysql_query($sql);
To retrieve a date reverse the process as follows:
$sql = "SELECT adate FROM database.table";
$rst = mysql_query($sql);
while ($arr = mysql_fetch_array($rst)) {
  $mydate = strtotime($arr['adate']);
  echo date('l, M j, Y', $mydate);
  /* will output, e.g., Tuesday, 31 Jan, 2006 */
}

0 Comments:

Post a Comment

<< Home