PHP - 从查询结果集中回显日期

时间:2018-03-27 14:55:29

标签: php sql-server coldfusion

PHP新手;来自ColdFusion的背景。我正在设置一个PHP 7测试页面,我连接到SQL Server数据库,执行选择查询,并在循环中回显查询结果。一切正常,除非我试图回显“datetime”类型的列或键入“date”,否则屏幕上什么都没有。这些是否需要某种日期格式化功能才能被回应?

另外,对于其他具有ColdFusion背景的人来说,我注意到在执行和输出查询时,与CF相比,PHP有些麻烦。任何让它变得容易的技巧?任何PHP框架特别适合这个?

<?php
// First attempt at SQL query. Note that MSSQL_CONNECT is removed in PHP 7; need to use sqlsrv_connect
$serverName = "localhost";
$connectionInfo = array( "Database"=>"somedb", "UID"=>"someid", "PWD"=>"somepassword");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$sql = "SELECT top 10 * from tQandCDownloads order by downloadId desc";

if( $conn ) {
     echo "Connection established.<br />";
}else{
     echo "Connection could not be established.<br />";
     die( print_r( sqlsrv_errors(), true));
}
echo "<br><br>";

$qry = sqlsrv_query($conn, $sql);
if ($qry === false) {
    die( print_r( sqlsrv_errors(), true));
}

while( $row = sqlsrv_fetch_array( $qry, SQLSRV_FETCH_ASSOC) ) {
    echo $row['downloadId'].", ".$row['fileName'].", ".$row['fileType'].", ".$row['downloadDate']."<br />";
}
//Remove downloadDate from above and results echo out as expected. But leave it in, and nothing echoes out to screen. Datatype is "datetime". Same thing happens with another column of type "date".
sqlsrv_free_stmt( $qry);
?>

1 个答案:

答案 0 :(得分:3)

好的,是的,它看起来像&#34; date&#34; datetime对象的属性不是直接访问的。相反,需要调用正确的方法来获取并显示日期,看起来像是#34; format()&#34;方法。将我的while循环更改为下面的内容,现在一切都响起来了:

while( $row = sqlsrv_fetch_array( $qry, SQLSRV_FETCH_ASSOC) ) {
    echo $row['downloadId'].", ".$row['fileName'].", ".$row['downloadDate']->format('Y-m-d').", ".$row['fileType'].", ".$row['forDate']->format('Y-m-d')."<br />";
}

顺便说一句,使用dBug.php就是我发现这两列的查询列值是对象的方式。模仿cfdump,这是我最喜欢的Coldfusion标签之一。 https://github.com/ospinto/dBug。我&#34;倾倒&#34;查询中的每一行都是这样的:

include_once("dBug.php");

while( $row = sqlsrv_fetch_array( $qry, SQLSRV_FETCH_ASSOC) ) {
    new dBug($row);
}