다음을 통해 공유


방법 매개 변수가 있는 쿼리 수행

이 항목에서는 SQL Server Driver for PHP를 사용하여 매개 변수가 있는 쿼리를 수행하는 방법을 요약하여 보여 줍니다.

매개 변수가 있는 쿼리를 수행하는 단계는 다음 네 단계로 요약할 수 있습니다.

  1. 실행할 쿼리인 Transact-SQL 문자열에 매개 변수 자리 표시자로 물음표(?)를 넣습니다.
  2. Transact-SQL 쿼리의 자리 표시자에 해당하는 PHP 변수를 초기화하거나 업데이트합니다.
  3. 2단계의 PHP 변수를 사용하여 Transact-SQL 문자열의 매개 변수 자리 표시자에 순서대로 해당하는 매개 변수 값의 배열을 만들거나 업데이트합니다.
  4. sqlsrv_query 또는 sqlsrv_prepare/sqlsrv_execute를 사용하여 쿼리를 실행합니다.

참고

매개 변수는 sqlsrv_prepare를 사용하여 암시적으로 바인딩됩니다. 이는 sqlsrv_prepare를 사용하여 매개 변수가 있는 쿼리를 준비하고 매개 변수 배열의 값을 업데이트하면 다음에 쿼리를 실행할 때 업데이트된 값이 사용될 것임을 의미합니다. 자세한 내용은 이 항목의 두 번째 예제를 참조하십시오.

다음 예제에서는 AdventureWorks 데이터베이스의 Production.ProductInventory 테이블에서 지정된 제품 ID에 대한 수량을 업데이트합니다. 수량과 제품 ID는 UPDATE 쿼리의 매개 변수입니다.

그런 다음 데이터베이스를 쿼리하여 수량이 올바르게 업데이트되었는지 확인합니다. 제품 ID는 SELECT 쿼리의 매개 변수입니다.

이 예제에서는 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));
}

/* Define the Transact-SQL query.
Use question marks as parameter placeholders. */
$tsql1 = "UPDATE Production.ProductInventory 
          SET Quantity = ? 
          WHERE ProductID = ?";

/* Initialize $qty and $productId */
$qty = 10; $productId = 709;

/* Execute the statement with the specified parameter values. */
$stmt1 = sqlsrv_query( $conn, $tsql1, array($qty, $productId));
if( $stmt1 === false )
{
     echo "Statement 1 could not be executed.\n";
     die( print_r( sqlsrv_errors(), true));
}

/* Free statement resources. */
sqlsrv_free_stmt( $stmt1);

/* Now verify the updated quantity.
Use a question mark as parameter placeholder. */
$tsql2 = "SELECT Quantity 
          FROM Production.ProductInventory
          WHERE ProductID = ?";

/* Execute the statement with the specified parameter value.
Display the returned data if no errors occur. */
$stmt2 = sqlsrv_query( $conn, $tsql2, array($productId));
if( $stmt2 === false )
{
     echo "Statement 2 could not be executed.\n";
     die( print_r(sqlsrv_errors(), true));
}
else
{
     $qty = sqlsrv_fetch_array( $stmt2);
     echo "There are $qty[0] of product $productId in inventory.\n";
}

/* Free statement and connection resources. */
sqlsrv_free_stmt( $stmt2);
sqlsrv_close( $conn);
?>

앞의 예제에서는 sqlsrv_query 함수를 사용하여 쿼리를 실행합니다. 이 함수는 문 준비와 실행 모두를 수행하기 때문에 일회용 쿼리를 실행할 때 유용합니다. sqlsrv_prepare/sqlsrv_execute 조합은 다른 매개 변수 값을 사용하여 쿼리를 다시 실행할 때 적합합니다. 다른 매개 변수 값을 사용하여 쿼리를 다시 실행하는 예는 다음 예제를 참조하거나 방법: 쿼리 다중 실행을 참조하십시오.

다음 예제에서는 sqlsrv_prepare 함수를 사용할 때 수행되는 암시적 변수 바인딩을 보여 줍니다. 이 예제에서는 여러 개의 판매 주문을 Sales.SalesOrderDetail 테이블에 삽입합니다. sqlsrv_prepare를 호출하면 $params 배열이 문($stmt)에 바인딩됩니다. 새 판매 주문을 테이블에 삽입하는 쿼리를 실행하기 전에 $params 배열은 항상 판매 주문 정보에 해당하는 새 값으로 업데이트됩니다. 따라서 이후에 쿼리를 실행하면 새 매개 변수 값이 사용됩니다.

이 예제에서는 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));
}

$tsql = "INSERT INTO Sales.SalesOrderDetail (SalesOrderID, 
                                             OrderQty, 
                                             ProductID, 
                                             SpecialOfferID, 
                                             UnitPrice)
         VALUES (?, ?, ?, ?, ?)";

/* Each sub array here will be a parameter array for a query.
The values in each sub array are, in order, SalesOrderID, OrderQty,
 ProductID, SpecialOfferID, UnitPrice. */
$parameters = array( array(43659, 8, 711, 1, 20.19),
                     array(43660, 6, 762, 1, 419.46),
                     array(43661, 4, 741, 1, 818.70)
                    );

/* Initialize parameter values. */
$orderId = 0;
$qty = 0;
$prodId = 0;
$specialOfferId = 0;
$price = 0.0;

/* Prepare the statement. $params is implicitly bound to $stmt. */
$stmt = sqlsrv_prepare( $conn, $tsql, array( &$orderId,
                                             &$qty,
                                             &$prodId,
                                             &$specialOfferId,
                                             &$price));
if( $stmt === false )
{
     echo "Statement could not be prepared.\n";
     die( print_r( sqlsrv_errors(), true));
}

/* Execute a statement for each set of params in $parameters.
Because $params is bound to $stmt, as the values are changed, the
new values are used in the subsequent execution. */
foreach( $parameters as $params)
{
     list($orderId, $qty, $prodId, $specialOfferId, $price) = $params;
     if( sqlsrv_execute($stmt) === false )
     {
          echo "Statement could not be executed.\n";
          die( print_r( sqlsrv_errors(), true));
     }
     else
     {
          /* Verify that the row was successfully inserted. */
          echo "Rows affected: ".sqlsrv_rows_affected( $stmt )."\n";
     }
}
/* Free statement and connection resources. */
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);
?>

참고 항목

참조

sqlsrv_rows_affected

개념

보안 고려 사항
설명서에 포함된 코드 예제 정보

관련 자료

디자인 고려 사항
데이터 형식 변환