the graphic design blog that speaks the truth

There are many tasks in PHP that seem hard to achieve, but are actually very simple to accomplish using the correct code.

There has long been the need to store the current date in a database. Whether it be to show the date a blog post was created, or adding a calendar entry. I have seen some solutions where the user manually enters the current date as part of the input form. There is a much more elegant, and more importantly simple solution to this task though.

Set up the database row

First things first, we need to create a new entry in our (MYSQL) database named date (or something similarly relevant), and store it as type varchar, as opposed to date.

Create the date

Next, in our php code, we grab the current date using the following php:

$date = date('d M Y');

This will output in the following format “22 May 2012”. You can alter it for your own needs by editing the contents of the format string (d M Y) which you can read about here.

Store the date

Now we simply store this variable in our new database row, with some standard SQL syntax, something like the following:

$query = "INSERT INTO my_table_name (title, content, date)
VALUES ('".$_POST['a_field']."', '".$_POST['another_field']."', '$date' )";
$insert = mysql_query($query);

That’s all that there is to it!

ABOUT THE AUTHOR

SHARE THIS ARTICLE

Voice Your Opinion

Thanks for your comment, it will appear here once it has been moderated.