简体   繁体   English

从 MySQL 数据库获取日期时间字段值

[英]Get datetime field value from MySQL database

I'm trying to get a datetime value from MySQL table.我正在尝试从 MySQL 表中获取日期时间值。 I stored it like 'yyyy-mm-dd hh:mm:ss' , but when I want to get it to print in a page, I get this '2019-04-01 00:00:00' or only '2019-04-01' .我将它存储为'yyyy-mm-dd hh:mm:ss' ,但是当我想将它打印在页面中时,我得到了这个'2019-04-01 00:00:00'或只有'2019-04-01' If I check the database, I can see the time stored properly, but when I want to print it, I only get zeros.如果我检查数据库,我可以看到正确存储的时间,但是当我想打印它时,我只能得到零。

if( $stmt = $mysqli->prepare( '
    SELECT
        estadistica_id, 
        aprobados, 
        suspendidos, 
        pendientes, 
        envios, 
        fecha, 
        curso.curso_id, 
        identificador_envio, 
        curso.titulo AS titulo_curso
    FROM estadistica
    LEFT JOIN curso ON estadistica.curso_id = curso.curso_id
    ORDER BY titulo_curso ASC' . $order_by
) ) {
    if( true === $stmt->execute() ) {
        $stmt->store_result();
        $stmt->bind_result( 
            $estadistica_id, 
            $aprobados, 
            $suspendidos, 
            $pendientes, 
            $envios, 
            $fecha, 
            $curso_id, 
            $identificador_envio, 
            $titulo_curso 
        );
        if( ( $num_rows = $stmt->num_rows ) > 0 ) {
            while( $stmt->fetch() ) {
                echo $fecha;
            }
        }
        $stmt->free_result();
        $stmt->close();
    }
}

$fecha prints '2019-04-01' and nothing more. $fecha 打印'2019-04-01' ,仅此而已。 I don't know how to print the date and time stored in the database.我不知道如何打印存储在数据库中的日期和时间。

Here goes the screenshots of the database, where you can see that the date and time is stored correctly.这是数据库的屏幕截图,您可以在其中看到日期和时间已正确存储。

database1database2

I'm lost :(我迷路了 :(

Appreciate all your help ;)感谢您的所有帮助;)

As R.Smith said in his comment, it should work if your column's format is varchar .正如 R.Smith 在他的评论中所说,如果您的列的格式是varchar ,它应该可以工作。 You must have another one.你必须有另一个。

You can use DateTime ( https://www.php.net/manual/en/class.datetime.php )您可以使用DateTime ( https://www.php.net/manual/en/class.datetime.php )

Example :例子 :

$date = new \DateTime($fecha);
echo $date->format('Y-m-d H:i:s');
// => 2019-04-01 18:42:03

When fetching a datetime value from database, the default format depends on your client.从数据库获取datetime值时,默认格式取决于您的客户端。 Most clients use MySQL default format ( 'YYYY-MM-DD HH24:MI:SS' ), but it looks like yours doesn't.大多数客户端使用 MySQL 默认格式 ( 'YYYY-MM-DD HH24:MI:SS' ),但看起来你的没有。

One solution would be to turn the date to a string with the expected format within the SQL query, using MySQL function DATE_FORMAT() :一种解决方案是使用MySQL 函数DATE_FORMAT()将日期转换为 SQL 查询中具有预期格式的字符串:

Consider:考虑:

SELECT
    estadistica_id, 
    ..., 
    DATE_FORMAT(fecha, '%Y-%m-%d %H:%i:%s'),
    ...
FROM estadistica
...

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

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