如何:將日期和時間類型當做字串來擷取
SQL Server Driver for PHP 1.1 版新增了這項功能。
從 1.1 版開始,您就可以透過在連接字串中指定選項,將日期和時間類型 (datetime、 date、 time、 datetime2 和 datetimeoffset) 當做字串來擷取。
若要將日期和時間類型當做字串來擷取
使用下列連接選項:
'ReturnDatesAsStrings'=>true
預設值是 false,表示 datetime、 Date、 Time、 DateTime2 和 DateTimeOffset 類型將傳回成 PHP Datetime 類型。
範例
下列範例示範指定將日期和時間類型當做字串來擷取的語法。
<?php
$serverName = "MyServer";
$connectionInfo = array( "Database"=>"AdventureWorks", 'ReturnDatesAsStrings '=> true);
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false )
{
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
sqlsrv_close( $conn);
?>
下列範例示範您可以透過在擷取字串時指定 UTF-8,將日期當做字串來擷取,即使連接是使用 "ReturnDatesAsStrings" => false
所建立也一樣。
<?php
$serverName = "MyServer";
$connectionInfo = array( "Database"=>"AdventureWorks", "ReturnDatesAsStrings" => false);
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
$tsql = "SELECT VersionDate FROM AWBuildVersion";
$stmt = sqlsrv_query( $conn, $tsql);
if ( $stmt === false ) {
echo "Error in statement preparation/execution.\n";
die( print_r( sqlsrv_errors(), true));
}
sqlsrv_fetch( $stmt );
// retrieve date as string
$date = sqlsrv_get_field( $stmt, 0, SQLSRV_PHPTYPE_STRING("UTF-8"));
if( $date === false ) {
die( print_r( sqlsrv_errors(), true ));
}
echo $date;
sqlsrv_close( $conn);
?>
下列範例示範如何透過在連接字串中指定 UTF-8 和 "ReturnDatesAsStrings" => true
,將日期當做字串來擷取。
<?php
$serverName = "MyServer";
$connectionInfo = array( "Database"=>"AdventureWorks", 'ReturnDatesAsStrings'=> true, "CharacterSet" => 'utf-8' );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
$tsql = "SELECT VersionDate FROM AWBuildVersion";
$stmt = sqlsrv_query( $conn, $tsql);
if ( $stmt === false ) {
echo "Error in statement preparation/execution.\n";
die( print_r( sqlsrv_errors(), true));
}
sqlsrv_fetch( $stmt );
// retrieve date as string
$date = sqlsrv_get_field( $stmt, 0 );
if ( $date === false ) {
die( print_r( sqlsrv_errors(), true ));
}
echo $date;
sqlsrv_close( $conn);
?>
下列範例示範如何將日期當做 PHP 類型來擷取。'ReturnDatesAsStrings'=> false
預設處於開啟狀態。
<?php
$serverName = "MyServer";
$connectionInfo = array( "Database"=>"AdventureWorks");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
$tsql = "SELECT VersionDate FROM AWBuildVersion";
$stmt = sqlsrv_query( $conn, $tsql);
if ( $stmt === false ) {
echo "Error in statement preparation/execution.\n";
die( print_r( sqlsrv_errors(), true));
}
sqlsrv_fetch( $stmt );
// retrieve date as string
$date = sqlsrv_get_field( $stmt, 0 );
if ( $date === false ) {
die( print_r( sqlsrv_errors(), true ));
}
$date_string = date_format( $date, 'jS, F Y' );
echo "Date = $date_string\n";
sqlsrv_close( $conn);
?>