SQL Server Driver for PHP를 사용하여 단일 쿼리를 수행하는 경우 sqlsrv_query 함수를 사용해야 합니다. sqlsrv_query 함수는 최소한의 코딩으로 쿼리를 실행할 수 있는 간편한 방법을 제공합니다. 또한 문 준비와 문 실행을 모두 수행하며 매개 변수가 있는 쿼리를 실행하는 데 사용할 수 있습니다. 이 항목에서는 sqlsrv_query 함수를 사용하여 일회성 쿼리를 실행하는 방법에 대해 설명합니다.
준비된 문을 여러 번 실행하는 방법은 방법: 쿼리 다중 실행을 참조하십시오.
예
다음 예제에서는 AdventureWorks 데이터베이스의 Sales.SalesOrderDetail 테이블에 단일 행을 삽입합니다. SQL Server와 AdventureWorks 데이터베이스가 로컬 컴퓨터에 설치되어 있다고 가정합니다. 명령줄에서 이 예제를 실행하면 모든 출력이 콘솔에 기록됩니다.
참고
다음 예제에서 sqlsrv_query를 사용한 단일 문 실행을 설명하기 위해 INSERT 문을 사용했지만 그 개념은 모든 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);
?>