This may be trivial, but when I want to store a timestamp value (returned by, say, time()) into a TIMESTAMP column in my MySQL table, which of these two are preferable:
function storeTime($timestamp) {
// Option one:
$query = "INSERT INTO faketable (datecol) VALUES (FROM_UNIXTIME(".$timestamp."))";
// Option two:
$query = "INSERT INTO faketable (datecol) VALUES (".date("YY-MM-DD HH:MM:II", $timestamp).")";
}
Is there even a difference?
EDIT: Sorry, meant date(), not strtotime()...
EDIT 2: NOW() doesn't cut the mustard, the actual timestamp is a paramater sent to my method. I don't know what it is in advance.
EDIT 3: I really shouldn't be asking questions at this time of night. The column in question is, in fact, a TIMESTAMP column, not a DATETIME column.
To answer your question; No there is no logical difference. They both return a string representation of a date https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_from-unixtime, which MySQL will happily convert to a DATETIME, or TIMESTAMP type. As for which is faster evidence would suggest MySQL; http://www.onextrapixel.com/2010/06/23/mysql-has-functions-part-5-php-vs-mysql-performance/, Faster to use MySQL's CURDATE() or PHP's date()?
Simplest is a FROM_UNIXTIME() in mysql. That'll be a single integer->date conversion. Doing it in PHP means integerr->string->datetime, which is far less efficient.
As well, your strtotime() is completely invalid. That's not now the function works. You'd end up with's in the database.
As for storing a "now" timestamp, why not just use a timestamp field type? it automatically sets itself to the current time when you insert/update a record.
How bout
INSERT INTO faketable (datecol) VALUES (UNIX_TIMESTAMP())
I think that's what you're looking for OP
Related
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! :)
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)
Which of the method is better to insert current time in mySQL.
PHP: time() in db column type INT(10)
or
MySQL: Now() in db type (datetime)
Thanks.
The second one is generally better as you don't need to convert it to a proper datetime before using other MySQL datetime functions on it.
storing a datetime is more useful for things like finding how many days have past. you can use all of date/time mysql functions in your queries.
The second - Now in datetime. Time returns a string. You'd need datetime most likely for different time-based calculations, plus there are tons of way to retrieve and format it with your queries.
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.
I'll explain my goal first: I want the user to query the database, and return rows only if those rows have been updated since their last query. No sense returning data they'd already have. So I created a column called 'lastupdated', a timestamp type which autoupdates every time any content in the row is updated. This works fine. Now, I want to form the query correctly. The user will have their previous query's timestamp saved, and via php will use it to compare their previous query's time with the time each row has been updated. If the row was updated after their last query, the row should be returned.
I made something like this,
SELECT * FROM users WHERE '2011-02-26 01:50:30' <= lastupdated
but its obviously much too simple. I checked the MySQL manual and found this page MySQL Time/Date Page. I'm sure the answer is here, but I've read through it any nothing really makes sense. I have a timestamp in the same format used by the MySQL timestamp type, but I don't know how I will compare them. Thank you very much for your help.
That query is exactly how you'd do it. As long as a stringified date-time is in MySQL's preferred format (yyyy-mm-dd hh:mm:ss), then it will be internally converted into a datetime value, and the comparisons will go ahead.
You'd only need the date/time functions you found if you want to do something more complicated than simple "greater/less than/equal" type comparison, e.g. "any records that have a December timestamp".
As Marc said, your code should work. But you probably want to do this programmatically with a variable for the time instead of the literal.
If you don't have the date-time specified as a string, but rather as a timestamp (e.g. from using the php time() function), then you can use the following query:
$query = "SELECT * FROM users WHERE FROM_UNIXTIME(" . $timestamp . ") <= lastupdated";
The key is the FROM_UNIXTIME() MySQL function.