How to: Execute a Single Query

When using the SQL Server Driver for PHP to execute a single query, the sqlsrv_query function should be used. The sqlsrv_query function provides a streamlined method to execute a query with minimum coding. This function does both statement preparation and statement execution, and can be used to execute parameterized queries. This topic describes how to use the sqlsrv_query function to execute a one-time query.

For information about executing a prepared statement multiple times, see How to: Execute a Query Multiple Times.

In the following example, a single row is inserted into the Sales.SalesOrderDetail table of the AdventureWorks database. The example assumes that SQL Server and the AdventureWorks database are installed on the local computer. All output is written to the console when the example is run from the command line.

Although the following example uses an INSERT statement to demonstrate the use of sqlsrv_query for a one-time statement execution, the concept applies to any Transact-SQL statement.

/* 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 
        (?, ?, ?, ?, ?, ?)";

/* 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";
     echo "Row insertion failed.\n";
     die( print_r( sqlsrv_errors(), true));

/* Free statement and connection resources. */
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);

Community Additions