PHP, using timestamp for mysql? - php

I've been trying to search for a straight answer, but for some reason the answer isn't coming to me. I was wondering what is the best way to store date/time into mysql?
I researched that timestamp in mysql is good because it will update depending on timezones too.
So I've set my column name as timestamp with datatype in mysql to timestamp, but what is the best syntax for storing current date/time to that?
"INSERT INTO table(timestamp) VALUES(now())" //or use timestamp()? or is there such thing?
?
Please help, thanks!

You could use datetime datatype in your table and just store it as NOW() which will store it as YYYY-MM-DD HHHH:MM:SS

Here are some considerations:
Set the column type to BIGINT so you can store 64-bit timestamps
You can insert using the PHP time() function, or MySQL's UNIX_TIMESTAMP() function
Name your column something other than timestamp. It is a permitted word1 see last section, but its also a type in MySQL.
If you store times as a Unix timestamp in MySQL, they are stored in UTC which makes dealing with timezone conversion very easy. In a 64-bit environment, PHP can handle dates up to the year 219,250,468.
Both of these queries are the same:
INSERT INTO `table` (`time`) VALUES(UNIX_TIMESTAMP());
// or
$time = time();
INSERT INTO `table` (`time`) VALUES($time);
Then to display it in PHP:
SELECT `time` from `table` WHERE `id` = 1;
echo date('Y-m-d H:i:s e', $row['time']); // 2012-07-31 23:59:59 America/Los_Angeles
Whatever timezone is set in PHP date_default_timezone_set() will be the timezone used when you output the date in PHP.

Related

MySQL PDO SELECT - return all dates as unix timestamp

For example I use this to insert in table:
INSERT INTO `mytable` (`name`, `type`, `date`) VALUES ('Smit', 12, now());
Then I need get all or some rows from this table:
$st = $db->prepare("SELECT * FROM `mytable` WHERE id=:id");
$st->bindParam(':id', $id, PDO::PARAM_INT);
$st->execute();
$result = $st->fetchAll(PDO::FETCH_ASSOC);
Where I receive $result[0]['date'] as string = "2016-09-10 21:00:00". Maybe PDO has some PDO::PARAM_ which can set all date fields to timestamp?
P.S. Yes I know about php strtotime() which I can use here, but in this case we do double conversion. I mean, if I understood this right, MySQL save datetime as unix timestamp and when we get it as string, then convert again to a timestamp, and it is not a good solution.
MySQL does not store DATETIME as a UNIX timestamp.
MySQL's TIMESTAMP data type may be stored internally like a UNIX-style timestamp, but in spite of this, the default output is formatted like YYYY-MM-DD HH:MM:SS. You will have to convert it back.
You can format the MySQL datetime as a UNIX timestamp using an SQL function:
$st = $db->prepare("SELECT UNIX_TIMESTAMP(date) FROM `mytable` WHERE id=:id");
$st->bindParam(':id', $id, PDO::PARAM_INT);
$st->execute([$id]);
$result = $st->fetchAll(PDO::FETCH_ASSOC);
See http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_unix-timestamp
It would be worth your time to review the other functions on that page. There are a lot of things you can do in SQL expressions.
Maybe PDO have some PDO::PARAM_ which can set all date fields to timestamp?
Nope, it doesn't.
There is no setting, neither in PHP, PDO or Mysql, that will tell mysql to return all dates as timestamps.
if i right understood, MySQL save datetime as unix timestamp
Nope, you understood it wrong.
and when we get it as string, then convert again in timestamp, it is not a good solution.
Don't worry about that. Just select your data in the format you need. As simple as that.
Do not optimize stuff that works all right. Do not solve problems that don't exist.
P.S. Yes I know about php strtotime() which i can use here, but in
this case we do double conversion. I mean, if i right understood,
MySQL save datetime as unix timestamp and when we get it as string,
then convert again in timestamp, it is not a good solution.
So if you want to avoid any conversions (manual or that under the hood) you shoud set up your field type in database as TIMESTAMP
https://dev.mysql.com/doc/refman/5.5/en/datetime.html

php timestamp utc

I have a PHP MySQL query that inserts some data into a MySQL database and it includes a timestamp.
Currently the INSERT query uses NOW() for the the timestamp column and it is saved in the database in the following format: 2012-07-24 13:13:02
Unfortunately for me the Server is not in my time zone and it is listed as America/Los_Angeles as shown print date_default_timezone_get();
I was hoping to do the following:
date_default_timezone_set('Europe/London');
$timefordbLondonEU = date('Y-m-d H:i:s', time());
and simply save into the database the $timefordbLondonEU in place of the NOW();
Is this a good way to save such data ?
Many Thanks,
Richard
[ADDED TEXT]
I changed the Type in the MySQL db to DateTime and did the following:
date_default_timezone_set('Europe/London');
$timefordbLondonEU = date('Y-m-d H:i:s', time());
It is working but Im still not getting the overall concept yet.
Assumptions based on your comments:
MySQL = Does not have a datatype UTC you simply use type INT.
Unix_TimeStamp() will save the current time or count? in UTC format such as 1343247227.
As UTC is a count from a common 0 point you can get any timezone from it. Assuming that you don't want a date before the reference 0 point in 1970.
My guess and lead on from what you have said is the best way to do it is save the time as UTC in an INT (1343247227) and then generate any time zones you want from there. Again assuming you don't need to store dates before the reference 0 point in 1970.
Equally why not store as datetime YYYY-MM-DD HH:MM:SS at a known timezone and then convert to UTC or other timezones. It all seems pretty messy =(
As #Petah said in the comments, store your times in UTC and covert them in the application as needed.
Unix timestamps are in UTC so I usually store my times in the database as timestamps. This saves the headache and confusion of first converting to UTC to insert, and then from UTC when selecting.
That is, make your time field an INT type, and use the function UNIX_TIMESTAMP() in MySQL when you insert, or get the timestamp from PHP using the time() function.
When you fetch the timestamp from the DB it will be in UTC, but when you display it in your PHP application using date(), it will display in the server timezone, or whatever you set with date_default_timezone_set.
Therefore the following two queries will work:
INSERT INTO `table` (id, time) VALUES(NULL, UNIX_TIMESTAMP());
// or
$time = time();
$query = "INSERT INTO `table` (id, time) VALUES(NULL, $time);
If you want to select it from the DB as a DATETIME, you can do this:
SELECT *, FROM_UNIXTIME(time) as dt FROM `table` WHERE 1
The resulting dt column will be in the format yyyy-MM-dd hh:mm:ss.
You can format the numeric timestamp in PHP using date()
If the PHP version you have is 64-bit, you aren't limited to the 1970 - 2036 range, PHP will support 64-bit timestamps, just make sure to use a BIGINT column in MySQL in that case.
Hope that helps.

PHP - Putting a date into a MySQL table

I have what is most likely a very simple question.. I am designing a simple blogging system and I am trying to put the current date into the table where the blog post is stored whilst waiting for administrator approval. but the method I have used puts 0000-00-00 into the date column! What I am using is as follows:
$query = "INSERT INTO blogentry VALUES ('".$mnam."','".date('d-m-Y h:m:s') ."\n"."','".$mcom."','".$approve."')";
I am relatively new to php so stumble accross errors like this all the time... but I cant seem to google this one!
Thanks guys!
So the easiest way to do this is just let MySQL handle it with the NOW() function:
INSERT INTO blogentry VALUES( ..., NOW(), ... )
Another option is to use TIMESTAMPs by changing your table - set the column to type TIMESTAMP with DEFAULT CURRENT_TIMESTAMP, and you can just ignore that column when inserting - it will automatically be filled with the current time. You will need to specify the columns you're inserting to in order to skip a column:
INSERT INTO blogentry( column1, column2 ) VALUES( column1value, column2value )
Finally, you NEED to sanitize your inputs. Preferably using prepared statements and PDO (http://php.net/manual/en/pdo.prepared-statements.php), or at least using mysql_real_escape_string.
From the MySQL manual on DATE, DATETIME
The DATE type is used for values with a date part but no time part.
MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The
supported range is '1000-01-01' to '9999-12-31'.
This means you have to insert the dates in YYYY-MM-DD format. You are using date('d-m-Y h:m:s') format. Change that to date('Y-m-d') and it should insert correctly.
If you want the time as well, then you need to change the column datatype to DATETIME and then insert using the format date('Y-m-d H:i:s').
As other mention, you can use an INT column type instead and store a Unix timestamp which is stored in UTC so it is more portable. You can then easily manipulate the timestamp to output the date any way you would like.
Try just storing a strtotime() result. It creates a unique timestamp, which can then be parsed however you need it in the future.
You might need to give the timestamp to the date function:
date('d-m-Y h:m:s', strtotime('now'))
Also, to do a standard datetime format:
date('Y-m-d H:i:s', strtotime('now'))

Converting Server MySQL TimeStamp To UTC

I've been using the timeago plugin (http://timeago.yarp.com/), it has been working fine on my localhost, which has its MySQL storing its data in the UTC timestamp, which the plugin needs to work.
However, when uploading my project to the server, a different type of timestamp is appearing in it MySQL database. I'm getting a timestamp like this: "Thursday, February 24, 2011 4:29 PM" from the server, whereas I need something like this: "2008-07-17T09:24:17Z"
Any idea how to convert the timestamps using php?
Edit: The timestamps stored in the wrong format in the database are automatically generated by mysql.
Edit 2: It's a field of type "timestamp" and default set to "CURRENT_TIMESTAMP" when row is being inserted in db
You are getting a weird string for MySQL, are you sure that it is in a Datetime field?
You can get a UNIX timestamp (seconds since epoch) from MySQL with the following function, this format is widely accepted over multiple platforms:
SELECT UNIX_TIMESTAMP( table.datetime_field ) as datetime_field FROM table
Using some PHP Functions you can convert this to the format you desire:
echo date( 'c', $record[ 'datetime_field' ] );
I think this would be sufficient for your problem.
SELECT UNIX_TIMESTAMP('your_date') AS your_date; in a query and
$date('whatever_format', $timestamp_from_mysql); in php
Internally a MySQL timestamp column is stored as UTC but when selecting a date MySQL will automatically convert it to the current session timezone.
When storing a date, MySQL will assume that the date is in the current session timezone and convert it to UTC for storage.
To select a timestamp column in UTC format
no matter what timezone the current MySQL session is in:
SELECT
CONVERT_TZ(`timestamp_field`, ##session.time_zone, '+00:00') AS `utc_datetime`
FROM `table_name`
You can also set the sever or global or current session timezone to UTC and then select the timestamp like so:
SELECT `timestamp_field` FROM `table_name`
I made a cheatsheet here: Should MySQL have its timezone set to UTC?
php code
<?php
$pdo = new \PDO($yourconnectionstring);
$sql = "SELECT
CONVERT_TZ(`timestamp_field`, ##session.time_zone, '+00:00') AS `utc_datetime`
FROM `table_name`";
$stmt = $pdo->prepare($sql);
$stmt->exec();
$timeVal = $stmt->fetchColumn();
if isset($timeVal) {
$dt = new \DateTimeImmutable($timeVal, new \DateTimeZone('UTC'));
echo $dt->format(\DateTime::ATOM);
}

Add date to mysql from php for sorting later

when inserting a date into a MySQL DB using PHP what is the best format so that I can sort by date later. I started using
$current_time = date("Y-m-d");
Is this the best practice?
If you are able to control your database fields then I would recommend using MySQL's built in Timestamp data type. You can set it to the current time by default.
CREATE TABLE IF NOT EXISTS `your_table` (
`date` timestamp NOT NULL default CURRENT_TIMESTAMP
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
If not then I would reccomend just storing the default PHP Unix formatted timestamp in an integer field.
$current_time = time();
The database handles dates internally for storing and sorting. Y-m-d format is good
You do not ever need to generate the current date or time in PHP to insert it into a query. Use the MySQL constants CURRENT_DATE and CURRENT_TIMESTAMP in the query instead.
INSERT INTO table (name, date) VALUES ('Bob', CURRENT_DATE)

Categories