/    Sign up×
Community /Pin to ProfileBookmark

MySQL Date/Time

I am fairly new to both MySQL and PHP but I have some usage down and I am pretty good with database and programming logic. I am just curious before I set up my database about the code that does this (as I know it exists, I am just not familiar with it).

I used to use separate date year and month fields in my database and then set up specific queries based on the values of these fields. However, since I just need to get these values out, how can I do this if I just put values in all as one DATETIME or TIMESTAMP field…..thanks in advance.

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@NogDogDec 21.2006 — You could do something like this to insert a date:
[code=php]
// assume you've populted the variables $year, $month, and $day from your form inputs:
$date = sprintf('%04d-%02d-%02d', $year, $month, $day);
$sql = "INSERT INTO table_name (date_field) VALUES('$date')";
$result = mysql_query($sql) or die("Query failed: $sql - ".mysql_error());
[/code]
Copy linkTweet thisAlerts:
@aj_nscauthorDec 21.2006 — Thanks for that. Makes good sense, I think I have another question though.

A more suitable question to ask maybe is:

Is it better to have the date year and month fields separate, because then it's easier to sort queries as you're making? (sorting is a big factor for me)

OR

Is it easier to sort entries via DATETIME?

Thanks
Copy linkTweet thisAlerts:
@NogDogDec 21.2006 — Definitely use a DATE or DATETIME field type, as that is the type of data you are representing. You can then compare and/or sort values easily within your SQL, such as:
[code=php]
$start = '2006-12-01';
$end = '2007-01-31';
$sql = "SELECT * FROM table_name WHERE date_field BETWEEN '$start' AND '$end' ORDER BY date_field";
$result = mysql_query($sql);
[/code]

Also, there are a whole bunch of [url=http://dev.mysql.com/doc/refman/4.1/en/date-and-time-functions.html]date and time functions[/url] you can use in your queries.
×

Success!

Help @aj_nsc spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.1,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...