I have a form in which I ask users for a starting date and time, sometimes a time isn't required so I seperated the fields into start_date and start_time where start_date is of type date and start_timewas a varchar but I feel that a time field is more appropriate.
So, what is the best way to store these fields in terms of flexibility and the ability to concatenate in the future?
Or is it a more standard practise to have a single field and combine the two values given by the user?
and start_timewas a varchar but I feel that a time field is more appropriate.
Yes, definitively. As soon as you need to perform some sort of “time operation” on the value at any point, like say add or subtract a certain amount of minutes, VARCHAR would become a hassle.
Or is it a more standard practise to have a single field and combine the two values given by the user?
Since the time is optional, I think you should store it separately - otherwise, how would you distinguish between a record that doesn’t have a time, and one that has it coincidentally say 00:00:00 in the time portion of a full datetime? You can NULL your separate time column, but you could not make “part” of a datetime value NULL.
You can use the below code to enter date and time in mysql database.
<?php
$db=mysqi_connect("localhost","username","password","database_name");
$date=date("Y-m-d H:i:s");
mysqli_query($db,"insert into table(Date_Today)values(''$date')");
?>
Related
I have mysql database, with birthdate column as date.
What would be the best way to save into this column, with optional year. Should I just put some random year on it? what is the best practice to save birthday in database.
I create 3 text field in cakephp, day, month, and year.. but not sure how to approach this, to save in database, since if I randomly put the year (maybe 0001, since 0000 is not accepted), when I pull it back, it will show the year.
Just an opinion, but if the year is optional (some will have it; some won't) I'd use a DATE type and set the year to zero. You can check for birthdays without years like this:
SELECT * FROM myTable WHERE YEAR(birthdate) = 0
Or if the birthdate column is indexed use this instead because it'll be optimizable:
SELECT * FROM myTable WHERE birthdate <= '0000-12-31'
If the year is forbidden for all values - in other words you'll never store the year - I'd recommend separate month and day columns.
Might it be best to use three columns, Day, Month, and Year, and treat Year as optional?
Edit: Although using two might be cleaner. one DATE column and just put a dummy year in (0000) and one YEAR column. Then assemble the two as you use them. That way you get all the formatting, sorting and data validation that the data types provide, but you can still ignore the year when you don't have it
The best approach is to have two fields:
birthdate which is a date
BirthdayHasYear which is a flag (such as a tinyint)
The reason for not depending on a rule like "when the year is zero then it is unknown" is that the data structure is very hard to understand -- in the future or if someone else looks at it. I would then be inclined to add a constraint that said "if BirthDayHasYear is true then the year on birthdate is 0 (or whatever).
Alternatively, I would have one field of birthdate and then only access the table through a view where such fields as:
BirthdayHasYear
Age
are defined as additional fields in the view. In other databases, I would use this approach with computed columns.
It seems like there are too many complicated ways of doing this, so I'm looking for a clean, succinct answer to this issue.
I write a blog, I click submit, and the title, content, and timestamp INSERTS INTO my blog table. Later, the blog is displayed on the blogindex.php page with the date formatted as MM-DD-YYYY.
So this is my 3 step question:
What is the best column type to insert the date into? (ex: INT, VARCHAR, etc)
What is the best INSERT INTO command to use? (ex: NOW(), CURDATE(), etc)
When I query the table and retrieve this data in an array, what is the best way to echo it?
I'm new at PHP/MySQL, so forgive me if I don't know the lingo and am too frustrated reading 1000 differing opinions of this topic that do not address my issue specifically, or only cover one of the 3 questions...
Here is my opinion on your three questions:
Use the correct data type: Date or DateTime. I would choose for the DateTime type as you store the time as well (might be very handy if you want to have some kind of order, when you added the posts).
It all depends whether you just want the Date (use CURDATE()) or the Date + Time (use NOW()).
You fetch the data and format it how you want it. Don't format it yet in the query, just use the correct PHP functions for it (for example with DateTime). How you fetch the data, doesn't matter too much; you can use PDO or MySQLi or ...
Always store and process dates and times in UTC and perform timezone adjustments in your presentation layer - it considerably simplifies things in the long-term.
MySQL provides a number of different types for working with dates and times, but the only one you need to worry about is DATETIME (the DATE type does not store time information, which messes up time zone conversion as information is lost, and the TIMESTAMP type performs automatic UTC conversion (which can mess up programs if the system time zone information is changed) and has a smaller range (1970-2038).
The CURDATE() function returns only the current date and excludes time information, however this returns information in the local timezone, which can change. Avoid this. The NOW() function is an improvement, but again, returns data in the current time zone.
Because you'll want to keep everything in UTC you'll actually want to use the UTC_TIMESTAMP function.
To return the value you'll need to execute SQL commands in sequence with variables, like so:
SET #now = UTC_TIMESTAMP()
INSERT INTO myTable ( utcDateTimeCreatedOrSomething ) VALUES ( #now )
SELECT #now
Date would probably be the best type, although datetime will work as record more accurate as well.
There isn't a 'best insert into', but what do you really want and how accurate you want the date to be. For a blog, I would say make it datetime and use NOW(). so visitors can see quite accurate of when this post is made.
surely you can easily find huge to run sql and fetch a select query from sql using php by google, so I'll leave this easy work to your self.
For echo the date, you can use the php date format such as:
$today = date("m-d-y"); // 03-10-01
I think Styxxy has it pretty well right, but here is a links for your PHP date formatting part...
How to format datetime most easily in PHP?
(Supporting link: http://php.net/manual/en/datetime.format.php )
Basically it's
echo date("d/m/Y", strtotime('2009-12-09 13:32:15'))
... although, I think the strtotime is unnecessary as it should already have the type of datetime.
In terms of the MySQL, yes, do it as a datetime col, use NOW() as the SQL keyword, and depending on how you want to get it from the database you could...
SELECT CAST(col_name AS DATE) .... or .... SELECT CAST(col_name AS DATETIME) <-- this last one is implied due to the col type.
good luck! :)
In my application I'm developing a functionality for creating "reminders".
A reminder has a date and a time. In my application, I have a form to create / edit reminders - this has two separate fields to input this information:
<input type="text" name="date"></input> <!-- datepicker plugin -->
<input type="text" name="time"></input> <!-- timepicker plugin -->
Now as a rule I have always used a DATETIME column whenever I have needed to store date/time, however this is the first time I'm having to store a user inputted date/time.
I figured it would be best to have seperate DATE and TIME columns, because it would be easier to insert / retrieve the data to / from my application. For example I won't have to combine the values from the two input fields to create a single value to insert in to the database. And likewise I won't have to split a single value in to two values to populate the form fields in edit mode.
But on the other hand won't it be easier to query the table if I used one column? What do you think?
You should build bottom-up (database at the bottom). Don't think about the application, just the database. Now, what makes sense at the database level. DateTime.
So you need to write extra code at the application level.
Please see it
Adding a Timepicker to jQuery UI Datepicker
http://trentrichardson.com/examples/timepicker/
convert your date time according to your mysql format and store it
$mydate = strtotime($_POST['date']);
$myfinaldate = date("d-m-y", $mydate);
$mytime = strtotime($_POST['time']);
$myfinaltime = date("H:i:s", $mytime);
Seperating columns is unlogical. You can use timestamp as datatype and you can use mktime function to parse date and time easily.
Doesn't it depends on the system you're creating.
If you want to store dates beyond 2038 I would store the datetime and time separate.
what if you are developing a reservation application and at one end you need to know on what date and at what time to schedule an appointment for a user, and at the other end, you need to match the user to a doctors schedule. You save the doctors schedule in a database and you need to know (amoung other things) when the doctor is available (on what days), and at what times. Let us forget about the on what days for a moment, and focus on the time shedule first...
You need to develop a programmable schedule so that if you know that the doctor works 6 months in a particular calendar year. (Jan - Jun), He or she may work (9-5 M,W,Fr), and (10-3 T,Th). Sat and Sunday the doctor is off. So you develop a table to hold the Daily time schedule with 2 columns to hold the daily starttime and daily end time for each day of the week. 14 columns in total and a primary and possibly secondary key. So now its time for some date arithmetic (This is where it gets hairy:-|...
You can say i your query: (mySQL)
Select such and such...
where form.theapptdatetime between doctorschedule_startime_tuesday and doctorschedule_endime_tuesday
and this will do a match to see if your datetime is within the date range of your doctorschedulestartime and endtime... but what if all you need is the time??
will the date arithmetic still work if the time value is stored as a datetime???
In other words if I have 01:00:00 as my doctorschedule_startime, is this a legitimate date value for my arithmetic to work, or will a date portion be forced upon me.
Perhaps I should store the time as a varchar, and convert it to a suitable datetime value and perform the arithmetic in the code instead of the query????
An example comes to my mind as to when have date and time split:
You could want to have DATE a part of the unique index, so that a user is only allowed to add 1 record to some table per date, but still you want to know the TIME he added it, so you keep DATE and TIME separate.
I have a DATETIME string and I need only the DATE in my script to perform some searches in my database. Currently, I have two scenarios in my mind, but don't know which of them is faster.
The first scenario:
In my MYSQL database, I have two columns: datetime (which is a DATETIME type) and date (which is a DATE type).
Then, in my PHP script, each time I save a record, I will insert my known string to the datetime field, and then convert it to fit the date field (I was thinking of something like: $date = date("Y-m-d", strtotime($datetime))).
This way, all the necessary pieces are stored in my database and I can retrieve them on the fly (both the datetime and the date fields).
The second scenario:
The MYSQL database should consist only of the datetime column.
My PHP script will insert the known string to the datetime field without any other modifications.
And when I retrieve my data, I would do something like: SELECT datetime, DATE(datetime) FROM ...
Conclusion
Which of these scenarios is faster and therefore should be used? Should date formats be made on save or on retrieve? Is MYSQL faster than PHP on formatting dates? Is it better to store everything in the database and retrieve as it is, or store only the minimum and format on retrieve? Which of these scenarios is the best practice?
Thank you!
It depends of your usecases:
If you are only going to need the date for reading, then go with a single datetime column, conversion from datetime to date is cheap enough.
If you are going to select rows at a given date (like WHERE date = '2011-08-01'), then go for a date column, as this will allow mysql to use the indexes on the date column if you have added one.
If you are going to select rows in a date range, then go for a datetime column. You could do things like WHERE datetime >= '2011-08-01' AND datetime < '2011-08-16'.
The second one is the best and fast as you are getting the value based on the requirement. Rather getting some value and working on it later.
imho
datetime, or even unsigned integer (unix timestamp) is better for range filtering
datetime allow date-time function, it could be useful for aggregate function
avoid formatted data from mysql (that's mean raw)
anything related to presentation is PHP duty
Definitely depends on your situation - if you will be reading (a lot) more than writing, you can store both. But I'd go for storing one field (datetime) and convert that, either in PHP or while retrieving it from MySQL (convert datetime to char in the format you like)
I am used to save dates in db as INT(11) with a time().
Considering the limitation of time() are there any better way to save that?
I would like to NOT use the database own DATE type (and all the db own date functions).
Thanks
Ok, from the comments, I understand that the problem with using time() is that we're looking to represent dates outside the 01/01/1970 to whenever/2038 range.
In this case, I think it's best to format dates for the DB as YmdHis, stored in a BIGINT (or just Ymd in INT if time isn't needed). You can get use date_create("now")->format($fmt) instead of time(), and where $fmt is either 'Ymd' for date-only or 'YmdHis' for date+time
This gives a latest date somewhere in 922,337,203AD and an earliest in -922,337,203BC with time, or 214,748AD to -214,748BC in an INT with no time.
Use $_SERVER['REQUEST_TIME'].
It's constant for the whole request and it's faster than time() (and UNIX_TIMESTAMP()) because it only requires an array lookup instead of a function call.
It is strange to avoid the standard time managing in DB. Have you ever considered all possible ways of representing if the correctly formated date field?
MySQL::Date and time functions
PostgreSQL::functions datetime
Storing the date in the correct format is more flexible and more efficient in some cases.
Datetimes are more readable for debugging and reading but the same amount of effort as timestamps for date formatting, the NOW keyword in the query makes things clean and tidy too, especially if you don't need the variable apart form the query:
INSERT INTO `mytable` (`id`,`title`,`created`) VALUES (NULL, 'my awesome record', NOW());
You could just use the built in database types for dates and times, or you could just make three integer columns in your table and save the date as integers. Whatever works and is easy to deal with.