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.

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

DateTime Database Record

Result!

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:

Done & dusted.

An introduction to ActionScript 3.0 – week 4 lesson 2

Learning actionscript? Want to know the gist of object creation and extending classes to do neat things? Then you’ve come to the right place…

Flash Week 4 Lesson 2

Download slides link: An Introduction to ActionScript 3.0 – Week 4, Lesson 2
Audience: Beginners who know a little about variables and how to perform some basic programming math.
Format: Powerpoint 2003 (so they can be opened in LibreOffice/OpenOffice, MS Office 2K3/2K7/2K10 etc.)
Template: OOo2 by Chih-Hao Tsai
Content License: These slides are released under a creative commons non-commercial attribution share-alike 3.0 license by me (r3dux) and come with no guarantee of correctness, fitness for purpose or anything of the sort.

EnJoY!