如何执行单个查询
使用 SQL Server Driver for PHP 执行单个查询时,应使用 sqlsrv_query 函数。sqlsrv_query 函数提供了一种使用最少编码执行查询的简化方法。此函数既准备语句又执行语句,并可用于执行参数化查询。本主题介绍如何使用 sqlsrv_query 函数执行一次性查询。
有关多次执行预定义语句的信息,请参阅如何多次执行一个查询。
示例
在以下示例中,在 AdventureWorks 数据库的 Sales.SalesOrderDetail 表中插入单个行。此示例假定本地计算机上已安装了 SQL Server 和 AdventureWorks 数据库。从命令行运行此示例时,所有的输出都将写入控制台。
备注
尽管以下示例使用 INSERT 语句来演示使用 sqlsrv_query 执行一次性语句,但此概念适用于任何 Transact-SQL 语句。
<?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 parameterized query. */
$tsql = "INSERT INTO Sales.SalesOrderDetail
(SalesOrderID,
OrderQty,
ProductID,
SpecialOfferID,
UnitPrice,
UnitPriceDiscount)
VALUES
(?, ?, ?, ?, ?, ?)";
/* Set parameter values. */
$params = array(75123, 5, 741, 1, 818.70, 0.00);
/* Prepare and execute the query. */
$stmt = sqlsrv_query( $conn, $tsql, $params);
if( $stmt )
{
echo "Row successfully inserted.\n";
}
else
{
echo "Row insertion failed.\n";
die( print_r( sqlsrv_errors(), true));
}
/* Free statement and connection resources. */
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);
?>