如何指定 PHP 数据类型
下面的步骤概述了在从服务器检索数据时如何使用 SQL Server Driver for PHP 来指定 PHP 数据类型:
- 使用 sqlsrv_query 或结合使用 sqlsrv_prepare、sqlsrv_execute 来设置和执行 Transact-SQL 查询。
- 使用 sqlsrv_fetch 提取一行数据以供读取。
- 使用 sqlsrv_get_field 并将所需的 PHP 数据类型指定为第三个参数(为可选参数),从返回的行中检索字段数据。如果未指定该可选的第三个参数,则将根据默认的 PHP 类型返回数据。有关默认的 PHP 返回类型的信息,请参阅默认的 PHP 数据类型。
有关用于指定 PHP 数据类型的常量的信息,请参阅 SQLSRV 常量的 PHPTYPE 部分。
示例
下面的示例从 AdventureWorks 数据库的 Production.ProductReview 表中检索行。在每个返回的行中,ReviewDate 字段均将作为字符串进行检索,Comments 字段将作为流进行检索。流数据将使用 PHP fpassthru 函数来显示。
此示例假定本地计算机上已安装了 SQL Server 和 AdventureWorks 数据库。从命令行运行此示例时,所有的输出都将写入控制台。
<?php
/*Connect to the local server using Windows Authentication and specify
the AdventureWorks database as the database in use. */
$serverName = "(local)";
$connectionInfo = array( "Database"=>"AdventureWorks");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false )
{
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
/* Set up the Transact-SQL query. */
$tsql = "SELECT ReviewerName,
ReviewDate,
Rating,
Comments
FROM Production.ProductReview
WHERE ProductID = ?
ORDER BY ReviewDate DESC";
/* Set the parameter value. */
$productID = 709;
$params = array( $productID);
/* Execute the query. */
$stmt = sqlsrv_query($conn, $tsql, $params);
if( $stmt === false )
{
echo "Error in statement execution.\n";
die( print_r( sqlsrv_errors(), true));
}
/* Retrieve and display the data. The first and third fields are
retrieved according to their default types, strings. The second field
is retrieved as a string with 8-bit character encoding. The fourth
field is retrieved as a stream with 8-bit character encoding.*/
while ( sqlsrv_fetch( $stmt))
{
echo "Name: ".sqlsrv_get_field( $stmt, 0 )."\n";
echo "Date: ".sqlsrv_get_field( $stmt, 1,
SQLSRV_PHPTYPE_STRING( SQLSRV_ENC_CHAR))."\n";
echo "Rating: ".sqlsrv_get_field( $stmt, 2 )."\n";
echo "Comments: ";
$comments = sqlsrv_get_field( $stmt, 3,
SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_CHAR));
fpassthru( $comments);
echo "\n";
}
/* Free statement and connection resources. */
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);
?>
在此示例中,以字符串的形式检索第二个字段 (ReviewDate) 将保留 SQL Server DATETIME 数据类型的毫秒精度。默认情况下,SQL Server DATETIME 数据类型将作为 PHP DateTime 对象进行检索,这样就失去了毫秒精度。
处于演示目的,将以流的形式检索第四个字段 (Comments)。默认情况下,SQL Server 数据类型 nvarchar(3850) 将作为字符串进行检索,这种方式在大多数情况下可行。
备注
通过 sqlsrv_field_metadata 函数可在执行查询之前获取字段信息,包括类型信息。