How to: Create and insert SQL DATE or DATETIME objects using PHP

I was helping a student with a bit of project work the other day and had to create a properly formatted Date object from input provided by some dropdown menus, so in the spirit of only ever solving the same problem once, this is how you go about it… I’ll use MySQL for this example, but if the DATEs or DATETIMEs or whatever you’re using have a slightly different format in your DBMS of choice, then the principle’s the same to generate a compatible object.

MySQL Time Formats

The MySQL DATE type has the format YYYY-MM-DD, so for example today (or at least when I’m writing this post) would be 2011-08-19.

The MySQL DATETIME type has the format YYYY-MM-DD HH:ii:SS, so if it’s 9:36am and 53 seconds into the 19th of August 2011, that would be 2011-08-19 09:36:53.

The formatting of the numbers (i.e. the sequence of digits) is super important, but the dashes and colons are optional. This means that when you’re creating a PHP object to represent a DATE or DATETIME, you could create an object which contains 2011-08-19 or 20110819 etc. and MySQL would accept them as the exact same thing.

Constructing a suitable object in PHP

To create our PHP object, we’re going to use the PHP date and mktime functions. For this example I’m just going to create some variables which hold any date or time values, but in the real world you’d probably get them from a dropdown menu or calendar control.

	// Create variables to store 1:15pm and 28 seconds on the 20th of August 2011
	// NOTE: If you don't enclose your values with apostrophes or quotes, then things will go wrong because
	// single digit values need the leading zeroes, for example the 08 below will turn into 8, and then
	// the whole thing's broken. See the bottom of this post for an alternative padding method for numbers.
	$theYear   = '2011'; // YYYY
	$theMonth  = '08';   // MM
	$theDay    = '20';   // DD
	$theHour   = '13';   // HH
	$theMinute = '15';   // ii
	$theSecond = '28';   // SS
	// Create an object suitable for insertion into a MySQL DATE field
	// The date 'YmD' parameters mean: year as YYYY, month as MM w/ leading zeroes, day as DD w/ leading zeroes
	// Full PHP date parameters can be found at:
	// The format of mktime is: hour, minute, second, month, day, year
	// Full PHP mktime parameters can be found at:
	$sqlDate = date('Ymd', mktime(0, 0, 0, $theMonth, $theDay, $theYear));
	// Create an object suitable for insertion into a MySQL DATETIME field
	// The date 'YmdHis' means: Ymd as above, hours as HH w/ leading zeroes, minutes as ii w/ leading zeroes, ss as seconds w/ leading zeroes
	$sqlDateTime = date('YmdHis', mktime($theHour, $theMinute, $theSecond, $theMonth, $theDay, $theYear));
	// Now you've got your DATE or DATETIME object, sling 'em in your database with something like this...
	$dbConn = mysql_connect("localhost", "root", "") or die("It is a good day to die!: " . mysql_error()); // Default WAMP settings
	// Choose the database to work with
	mysql_select_db("MyLovelyDatabase", $dbConn) or die("It is a good day to fail to connect to your DB!: " . mysql_error());
	// Create the insert statement
	$sqlStatement = "INSERT INTO TestTable (someDate, someDateTime) VALUES ('$sqlDate', '$sqlDateTime')";
	// Execute the statement
	$result = mysql_query($sqlStatement, $dbConn);
	// Display result of the statement. If this is 1 then the insertion was successful, otherwise it wasn't
	echo "Statement executed and gave the following result: " . $result;
	// Shut down the connection to the database

Which when we then take a look at the database shows us:

DateTime Database Record


Automatically padding out numerical data with leading zeroes

If you need to work directly with numerical data (as opposed to strings), then you can use the following function (written by matrebatre over on the str_pad page) to pad out your data:

	function padNumber($theNumber, $numDigits)
		// str_pad format: value, desired number of characters, what to pad with, where to place the padding
		return str_pad((int) $theNumber, $numDigits, "0", STR_PAD_LEFT);
	$value = 5;
	$paddedValue = padNumber($value, 1); echo $paddedValue . "<br/>"; // 5
	$paddedValue = padNumber($value, 2); echo $paddedValue . "<br/>"; // 05
	$paddedValue = padNumber($value, 3); echo $paddedValue . "<br/>"; // 005

Done & dusted.