简体   繁体   English

PHP 如何从 Mysql 返回 datetime(6)?

[英]PHP How to return datetime(6) from Mysql?

When I query a dateTime(6) PHP is truncating my 6 fractional seconds.当我查询 dateTime(6) 时,PHP 会截断我的 6 秒小数部分。

Here is an example of my php code:这是我的 php 代码示例:

$sql = 'SELECT date FROM tbl';
        $statement = $connection->prepare($sql);
        $statement->execute();
        $statement->store_result();
        $statement->bind_result($date);
        while ($statement->fetch()) 
        {
        echo $date."\n";
        }

This returns 2014-01-08 21:31:15 instead of 2014-01-08 21:31:15.995000 which is what is stored in the table.这将返回 2014-01-08 21:31:15 而不是 2014-01-08 21:31:15.995000 这是存储在表中的内容。 How can I get what is actually stored in the table?如何获取表中实际存储的内容?

The problem is with the PHP Adapter you are using to communicate with Mysql.问题出在您用来与 Mysql 通信的 PHP 适配器上。 As far as I can see you are using PDO adapter to fetch the query result.据我所知,您正在使用 PDO 适配器来获取查询结果。 However, this adapter does not support fractional seconds (YYYY-MM-DD HH:MM:SS.F).但是,此适配器不支持小数秒 (YYYY-MM-DD HH:MM:SS.F)。

The PDO adapter supports YYYY-MM-DD HH:MM:SS and automatically formats the value of datetime columns to this format. PDO 适配器支持 YYYY-MM-DD HH:MM:SS 并自动将日期时间列的值格式化为这种格式。

This is a bug in PDO adapter itself.这是 PDO 适配器本身的一个错误。 Please find the link below for reference: http://grokbase.com/t/php/php-bugs/11524dvh68/php-bug-bug-54648-new-pdo-forces-format-of-datetime-fields请找到以下链接以供参考: http : //grokbase.com/t/php/php-bugs/11524dvh68/php-bug-bug-54648-new-pdo-forces-format-of-datetime-fields

You can format it to include it.您可以将其格式化以包含它。 The %f includes the six-digit microseconds . %f 包括六位微秒

 SELECT DATE_FORMAT(date, '%Y-%m-%d %H:%i:%s.%f') FROM tbl

It's crazy this still isn't officially supported by mysqli in PHP 7.1, but anyway, here's a work around. PHP 7.1 中的mysqli仍然没有正式支持这很疯狂,但无论如何,这里有一个解决方法。

select concat(`DateTime6`)`DateTime6` from ...

Basically casting it as a string worked for me, as ugly as that is.基本上将它转换为对我有用的字符串,尽管如此丑陋。

This bug was finally fixed in PHP v7.3.0.这个错误最终在 PHP v7.3.0 中得到修复。

For related bug details: https://bugs.php.net/bug.php?id=76386相关错误详情: https : //bugs.php.net/bug.php?id=76386

DateTime does not support split seconds (microseconds or milliseconds etc.) DateTime 不支持分秒(微秒或毫秒等)

http://www.php.net/manual/en/class.datetime.php http://www.php.net/manual/en/class.datetime.php

https://bugs.php.net/bug.php?id=51950 https://bugs.php.net/bug.php?id=51950

in your case you might save the value in MySQL as VARCHAR and case / convert it to datetime when reading it.在您的情况下,您可以将 MySQL 中的值保存为 VARCHAR 并在读取时将其大小写/转换为日期时间。

I had the same problem and nothing helped me except converting我遇到了同样的问题,除了转换之外没有任何帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM