I want some insights on inserting data into MySQL for later comparison. I know that those format date(Y-m-d) and strtotime(date(Y-m-d)) have its own specific kinda usage. But I'm new to the field of MySQL and PHP. So I need a list of pros and cons of use among you guys. Which one are you using and please give me a little why.
Which is more efficient and correct to use date(Y-m-d) or strtotime(date(Y-m-d))?
I want to know if it gets any advantage in comparing time between these queries:
1. `select * from table where '2012-11-01' between date1 and date2`
2. `select * from table where '1351702800' between date1 and date2`
Could you please point me out which one is faster when it's dealing with a large MySQL dataset?
In my opinion Date types are better to use. The ms you need to convert a Timestamp back to a readable format will lose against the time that the SQL query does take longer to read the entirely Date from the database.
Timestamp is more optimized, however you need PHP to convert - slower.
Date type is already in readable format, no need to convert - faster.
Edit: And MySQL have great functions to deal with Date types!
Related
I am trying to optimise how I use dates across my SQL/PHP site. I'm familiar with date() and strtotime() functions, and have created projects which have stored data on the server side in both unix and datetime. I know that changing date doesn't use massive amounts of resource, but I'm trying to understand how to code in the most efficient way.
What I'm trying to work out now is what the quickest/most efficient practise is for storing dates on a server, i.e: What is the most effective combination of SQL FROM_UNIXTIME, CONVERT, UNIX_TIMESTAMP and PHP strtotime and date functions, for a typical table involving frequent CRUD of the date fields. Take the following example:
I have an SQL table which contains 3 date columns. All 3 of these can be updated quite regularly by multiple users of the site, and entries are also entered in to it as follows:
mysql_query("INSERT INTO `regular` (
`regularid`,
`propertyid`,
`userid`,
`billdate`,
`billfrequency`,
`enddate`,
`amount`,
`description`,
`payee`,
`payer`,
`lastpayment`
)
VALUES (
'', '{$_POST['propertyid']}', '$varuserid', FROM_UNIXTIME($date), '{$_POST['billfrequency']}', 'FROM_UNIXTIME($edate)', '$amount', '{$_POST['description']}', '{$_POST['payee']}', '{$_POST['payer']}', 'FROM_UNIXTIME($ldate)'
)") or die(mysql_error);
Print "A regular payment for £".$_POST['amount']." has been created<br/>\n";
Entering in to the database I parse the date fields from a user entry form to a variable in mm / dd / yyyy format, validate it with the strtotime() or mktime() functions, and then submit it using from_unixtime.
However, then displaying information from the database I use:
date("d-m-Y", strtotime($val['billdate']))
That means I take a dd/mm/yyyy date format from the user and another one from the database. I then convert these to unixtime using strtotime, and then convert it back to British date format using date - This is surely doubling? if not tripling? the server query.
My question is in 2 parts.
Firstly, is it quickest a) storing all date formats in unixtime in sql and converting to date format through the server side query or b) storing all date formats in date format and converting to unixtime only when accessing them
(I thought the latter would be best, but my example above shows that even doing that I seem to be using more server time than I ought to)
Secondly, could you point me in the right direction for how I should carry out my own time benchmarks of scripts - I'm only really beginning to understand testing as I'm still relatively new to Php, but I'm keen to learn.
Thanks so much!
Use MySQL's "unix_timestamp()", it's short and can be converted to readable full date within a second by using php, bash etc.
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 am creating a mysql db with a php frontend. The data it will use is extracted from another larger db and contains a date/time field which looks like this - 20120301073136 - which records when an event happened.
I understand that this might be a UNIX timestamp? Not sure.
I want to be show this field in the tables in my PHP webpage as a readable date and time -
ie something like 01-Mar-2012 07:31:36 or similar
Should I try and convert it with SQL command or let PHP format it? And, what is the code to do so?
BTW, it is important that I can sort the data (in SQL and in the PHP table) into date order - ie in the order that these events happened.
Thanks in advance for your help - Ive learnt a lot here already
J
You can convert it to a datetime directly in your SQL query. Example:
select cast(20120301073136 as datetime)
You can also order that with no need to convert it since it is a number in the format YYYYMMDDHHmmss
select * from yourTable
order by yourDateTimeField
You should make use of the MYSQL DATE functions. Check the docs before asking simple questions. http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html.
Also you can sort the dates directly in your query using ORDER BY.
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 have found a proper solution to my "problem" but even after reading mysql pages, I don't understand the logic behind it.
I currently store registration information in my system in a "datetime" formatted field in one of my tables (YYYY-MM-DD hh:mm:ss).
When I want to display the data on one of my php pages, simply posting the exact field data shows the format mentioned above.
I would THINK simply using date("Y-m-d",$row["DATE"]) where $row["DATE"] corresponds to the particular row value would return the desired format.
Instead I have to use:date("Y-m-d", strtotime($row["DATE"])).
Why is this? My $row["DATE"] field is not a string in the first place. Should I be able to simple rearrange the data stored in a datetime field? Wasn't that the purpose of rebuilding my entire tableset to accomodate datetime?
MySQL has a built in function called date_format which you can use to display the date how you want to.
SELECT DATE_FORMAT(date_field, '%Y-%m-%d') as date_field FROM table_name
The manual has the list of formats and the variables needed to display it that way. Using this method there will be no need to have PHP convert it etc. Plus it is less code on PHP side for something MySQL can handle easily.
EDIT
Sorry, just read you were looking for an explanation.
PHP's date function takes in a UNIX timestamp, which MySQL is not using. MySQL uses a real date format IE: YYYY-MM-DD HH:MM:SS, as you know, this is to be compliant for years later. The UNIX timestamp has a limited range from something like 1969 to 2037 that it is valid for, which makes it really useful for "timestamping" of items such as a chat box message or items they are not expected to be around post those dates, where as the MySQL DATETIME should not die out until the year changes to 5 digits or the world ends.
Read the WIKI on UNIX timestamp for more information on it.
MySQL does allow you to select dates in unix timestamp format, which allows them to be used more easily in PHP, exactly as you requested.
The previous answer seemed to ignore this point, or downplay it due to the range restriction on the unix timestamp, but if it's what you're looking for...
SELECT UNIX_TIMESTAMP(datefield) as u_datefield FROM table
will give you the date in timestamp format, which you can use as you suggested in PHP:
<?php
$showdate = date("Y-m-d",$row['u_datefield']);
?>
As the previous answer suggests, unix timestamps do have a limited range, so if you need dates prior to 1970 or after 2038 it may not be suitable, but for everyday use today it's great.
The main advantage of using timestamps over date strings is that timestamps can be added and subtracted, which is much harder with a date in string format.