PHP 中的 DATETIME 字段 MS-SQL 出现问题

Issue with DATETIME field MS-SQL in PHP

我在 MSSQL 中有以下查询:

SELECT DataFeed.AccountTranID, DataFeed.Datetime as MyDT
FROM admin_all.DataFeed
where cast(DataFeed.Datetime as Date) = cast(getdate() as Date)

给出以下输出:

AccountTranID   MyDT
124552  2019-07-31 00:00:04.660
124553  2019-07-31 00:00:07.933
124554  2019-07-31 00:00:25.623
124555  2019-07-31 00:00:29.013
124556  2019-07-31 00:00:29.206
124557  2019-07-31 00:00:44.893
124558  2019-07-31 00:00:56.796
124559  2019-07-31 00:01:11.353
124560  2019-07-31 00:01:12.260
124561  2019-07-31 00:01:19.413
124562  2019-07-31 00:01:19.510
124563  2019-07-31 00:01:28.596
124564  2019-07-31 00:01:30.710
124565  2019-07-31 00:01:46.976
124566  2019-07-31 00:01:49.823
124567  2019-07-31 00:01:57.340

当尝试使用此 PHP 代码获取 MyDT 字段时,我无法获得输出(空白)。使用 AccountTranID,没问题。

这里是 Php 代码:

$tsql = "SELECT DataFeed.AccountTranID, DataFeed.Datetime as MyDT 
FROM admin_all.DataFeed where cast(DataFeed.Datetime as Date) = cast(getdate() as Date) ";
// Executes the query
$stmt = sqlsrv_query($conn, $tsql);

// Error handling
if ($stmt === false) {
    die(formatErrors(sqlsrv_errors()));
}
?>

<h1> Results : </h1>

<?php

while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {


    echo  $row['AccountTranID'].'-'. $row['MyDT'].'<br>';

}

sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);

我们发现,查询的第二个选择的元素是DateTime类型,因此您必须将其解析为字符串。

你可以用这个代码来做:

while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
    echo  $row['AccountTranID'].'-'. $row['MyDT']->format('Y-m-d H:i:s').'<br>';
}

说明:

当您使用 sqlsrv_query() 从 SQL 服务器检索数据时,您可以控制 datedate/time 值是 returned 来自 SQL 服务器。这可以通过在连接字符串中设置 'ReturnDatesAsStrings' 选项来完成。此选项的默认值为 falsesmalldatetimedatetimedatetimedatetime2datetimeoffset 类型作为 PHP DateTime 对象返回。当此选项为 true 时,这些值将作为字符串返回。

检索 datedate/time 值作为 PHP 日期时间对象:

<?php
    // Connection
    $server = '127.0.0.1\ikosoft,1066';
    $cinfo = array(
        "ReturnDatesAsStrings"=>false,
        "Database" => "database",
        "UID" => "username",
        "PWD" => "password"
    );
    $conn = sqlsrv_connect($server, $cinfo);
    if( $conn === false )
    {
        echo "Error (sqlsrv_connect): ".print_r(sqlsrv_errors(), true);
        exit;
    }

    ....
    // Fetch data
    while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
        echo  $row['MyDT']->format('Y-m-d H:i:s')."<br>";
    }
    ...
?>

检索 datedate/time 值作为字符串:

<?php
    // Connection
    $server = '127.0.0.1\ikosoft,1066';
    $cinfo = array(
        "ReturnDatesAsStrings"=>true,
        "Database" => "database",
        "UID" => "username",
        "PWD" => "password"
    );
    $conn = sqlsrv_connect($server, $cinfo);
    if( $conn === false )
    {
        echo "Error (sqlsrv_connect): ".print_r(sqlsrv_errors(), true);
        exit;
    }

    ....
    // Fetch data
    while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
        echo  $row['MyDT']."<br>";
    }
    ...
?>