How To Assign The Current Date and Time to a MySQL Datetime Field using PHP

This is a no-brainer, but I always forget how to do it. MySQL datetime fields are stored in this format: 2010-02-18 10:33:18. Here’s a trivial example showing you how to populate a datetime field with the current date in the correct format, then write it to a table:

 // Assign current date to a MySQL date field:
 $eventdate = date('Y-m-d H:i:s');
 //... (mysql connection code goes here)
 mysql_query("INSERT INTO Events (Event, EventDate) VALUES ($eventtext, $eventdate)");

Another question might be: “Why?” – when MySQL has the now() function. I needed to do this in Drupal, because I’m using the drupal_write_record function to update a table in a custom module. This requires assigning PHP values to fields in my table, rather than using any built-in MySQL functions.

One thought on “How To Assign The Current Date and Time to a MySQL Datetime Field using PHP

Leave a Reply

Your email address will not be published. Required fields are marked *