簡體   English   中英

從 MySQL 數據庫獲取日期時間字段值

[英]Get datetime field value from MySQL database

我正在嘗試從 MySQL 表中獲取日期時間值。 我將它存儲為'yyyy-mm-dd hh:mm:ss' ,但是當我想將它打印在頁面中時,我得到了這個'2019-04-01 00:00:00'或只有'2019-04-01' 如果我檢查數據庫,我可以看到正確存儲的時間,但是當我想打印它時,我只能得到零。

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 打印'2019-04-01' ,僅此而已。 我不知道如何打印存儲在數據庫中的日期和時間。

這是數據庫的屏幕截圖,您可以在其中看到日期和時間已正確存儲。

database1database2

我迷路了 :(

感謝您的所有幫助;)

正如 R.Smith 在他的評論中所說,如果您的列的格式是varchar ,它應該可以工作。 你必須有另一個。

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

例子 :

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

從數據庫獲取datetime值時,默認格式取決於您的客戶端。 大多數客戶端使用 MySQL 默認格式 ( 'YYYY-MM-DD HH24:MI:SS' ),但看起來你的沒有。

一種解決方案是使用MySQL 函數DATE_FORMAT()將日期轉換為 SQL 查詢中具有預期格式的字符串:

考慮:

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