Escolar Documentos
Profissional Documentos
Cultura Documentos
Introduction
The Microsoft Drivers for PHP for SQL Server allow PHP developers to access data in all editions of SQL Server, beginning with SQL Server 2005. The Microsoft Drivers for PHP for SQL Server include two PHP extensions for accessing data in SQL Server: a procedural interface (SQLSRV) and an object oriented interface (PDO). Both the SQLSRV and PDO APIs provide a comprehensive data access solution from PHP, and include support for many features including Windows Authentication, transactions, parameter binding, streaming, metadata access, connection pooling, UTF-8 encoding, error handling, and SQL Azure access. This paper explains how to load and configure each of the drivers, and discusses how to leverage several of the features mentioned above. Parts of the example applications (Example Application (SQLSRV Driver) and Example Application (PDO Driver)) in the product documentation will be used to demonstrate these programming scenarios. For more information and a complete list of driver features and functions, see the SQLSRV API Reference and PHP Data Objects (PDO) Reference sections in the product documentation on MSDN. The Microsoft Drivers for PHP for SQL Server rely on the Microsoft SQL Server Native Access Clients ODBC driver to handle the low-level communication with SQL Server. As a result, the Microsoft Drivers for PHP for SQL Server are only supported on Windows.
Microsoft Corporation 2010
Microsoft provides support for these drivers under its normal support methods. While the source code for these drivers has been made available on the codeplex.com website, Microsoft supports only the signed versions of the drivers from the MSDN download site and the Web Platform Installer. This paper is divided into two major sections: Using the SQLSRV Driver and Using the PDO Driver. This paper also assumes that the reader is familiar with programming in PHP, that the reader has a computer that meets the System Requirements listed for using the driver, and that the AdventureWorks example database is installed.
Note There are exceptions to this rule. For example, the warning generated by changing the database context is never treated as an error. For more information about these options and settings, see Configuring the Driver in the product documentation. Configuration options can be set in the php.ini file, or they can be set in a PHP script with the sqlsrv_configure function. The figure below shows the Dynamic Extensions section of the php.ini file modified to load the driver, log activity on all subsystems, log all activity (errors, warnings, and notices), and turn off the WarningsReturnAsErrors behavior.
Figure 1 (SQLSRV): The Dynamic Extensions section of the php.ini. For more information about how to change the default settings, see Logging Activity and How to: Configure Error and Warning Handling Using the SQLSRV Extension in the product documentation. One way to be sure that the driver is loaded and to see the configuration settings is to run a script that calls the phpinfo() function. To do this, follow these steps: 1. Open a text file and copy the following code into it: <?php phpinfo(); ?> 2. Save the file as info.php in your Web servers root directory. 3. Open a browser and go to http://localhost/info.php. 4. Scroll down the resulting page to find the sqlsrv section. The following figure shows the sqlsrv section of the phpinfo() page. This output confirms the driver is loaded and the configuration settings are set to default values.
Microsoft Corporation 2010
For more information about creating a connection, see the Connection Pooling (SQLSRV and PDO) section later in this paper and Connecting to the Server in the product documentation. Note The FormatErrors function that is shown in the example is a custom function for formatting error output. It is described in the Handling Errors and Warnings (SQLSRV) section later in this paper.
The following code (from the Example Application (SQLSRV Driver) in the product documentation) demonstrates the use of the sqlsrv_query function: $params = array(&$_POST['query']);
$tsql = "SELECT ProductID, Name, Color, Size, ListPrice FROM Production.Product WHERE Name LIKE '%' + ? + '%' AND ListPrice > 0.0";
Note If query parameter variables are not prefixed with &, the SQLSRV driver will attempt to bind all parameters by reference. If a parameter variable is not prefixed with &, the driver will generate a warning. The sqlsrv_query and sqlsrv_prepare functions each accept four parameters: $conn, $tsql, $params (optional), and $options (optional). $conn This required parameter is a PHP connection resource created with the sqlsrv_connect function (see the Creating a Connection (SQLSRV) section). $tsql This required parameter is a string that defines a Transact-SQL query. Question marks (?) are used as placeholders for parameter values. $params This optional parameter is an array of values that correspond (in order) to the parameter placeholders (question marks) in the query defined by the $tsql parameter. Each value in the $params array can be a literal value (such as 5), a PHP variable (such as $myVar), or an array with the following structure: array($value [, $direction [, $phpType [, $sqlType]]]) This array is used to specify the parameter value, the parameter direction (in the case where the parameter is being passed to a stored procedure), the PHP type of the parameter, and the SQL Server type of a value sent to the server. For more information about this array, see the Sending Images to the Server section. For more information, see Using Directional Parameters, How to: Send Data as a Stream, and How to: Specify SQL Server Data Types When Using the SQLSRV Extension in the product documentation. $options This optional parameter is an associative array that sets properties on the query. Three keys are supported: QueryTimeout, SendStreamParamsAtExec, and Scrollable. The QueryTimeout key sets the maximum time in seconds that a query is allowed to run. The SendStreamParamsAtExec key determines if all stream data is sent at the time of query execution or if subsequent calls to sqlsrv_send_stream_data are necessary to send all stream data. (For more information, see How to: Send Data as a Stream.) The Scrollable key determines what type of cursor the result set is read with (forward, static, dynamic, or keyset). (For more information, see Specifying a Cursor Type and Selecting Rows.)
Note By default, these functions provide forward-only access to the rows of a result set. To enable scrolling through a result set, use the Scrollable option when preparing the query. For more information, see Specifying a Cursor Type and Selecting Rows in the product documentation.
When choosing which option to use, consider the following: The sqlsrv_fetch_array and sqlsrv_fetch_object functions pull an entire row of data into script memory. This may not be desirable for rows that contain large amounts of data. Data returned by the sqlsrv_fetch_array and sqlsrv_fetch_object functions will be typed according to the defaults PHP data types assigned by the driver. For more information, see Default PHP Data Types in the product documentation. Using the combination of sqlsrv_fetch and sqlsrv_get_field allows you to specify the PHP data type of the returned data, including specification of the data as a stream.
For more information about retrieving data, see Retrieving Data in the product documentation.
The $fetchType parameter (optional) is a driver-defined constant that specifies what type of array will be returned: associative, numeric, or both. The corresponding constants are SQLSRV_FETCH_ASSOC, SQLSRV_FETCH_NUMERIC, and SQLSRV_FETCH_BOTH. By default, an array with both types of indices is returned. The $row parameter (optional) is used to specify the row to access in a result set that uses a scrollable cursor. For more information, see sqlsrv_fetch_array in the product documentation. The $offset parameter (optional) is used in combination with the $row parameter to specify which row to retrieve. For more information, see sqlsrv_fetch_array in the product documentation.
Note If query parameter variables are not prefixed with &, the SQLSRV driver will attempt to bind all parameters by reference. If a parameter variable is not prefixed with &, the driver will generate a warning. The sqlsrv_get_field takes three parameters, $stmt, $fieldIndex, and $getAsType (optional): The $stmt parameter is a PHP resource corresponding to an executed statement. The next (or first) row of data is made available to the sqlsrv_get_field function by first passing the $stmt parameter to the sqlsrv_fetch function. The $fieldIndex specifies the index of the field to be retrieved. Indices start at zero. The $getAsType parameter (optional) is used to specify the PHP type (and encoding, in this case) of the returned data. If this parameter is not provided, data will be returned according to its default PHP type. For more information, see Default PHP Data Types in the product documentation.
For more information about retrieving images and binary/large data, see Retrieving Data as a Stream in the product documentation. Retrieving data with the combination of the sqlsrv_fetch and sqlsrv_get_field functions can be used to specify the PHP type of returned data, not only for retrieving data as a stream. For more information, see How to: Specify PHP Data Types in the product documentation.
$tsql = "SELECT ProductID FROM Production.Product"; $params = array(); $queryOptions = array("Scrollable"=>"keyset"); $stmt = sqlsrv_query($conn, $tsql, $params, $queryOptions); $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC,
10
SQLSRV_SCROLL_ABSOLUTE, 4);
print_r($row);
11
sqlsrv_execute in the example is done to demonstrate how these functions are used together.) Note If query parameter variables are not prefixed with &, the SQLSRV driver will attempt to bind all parameters by reference. If a parameter variable is not prefixed with &, the driver will generate a warning. This example highlights the drivers streaming capabilities. The customers comments ($comments) are opened as a text stream ($stream), which is a parameter in the query. By default, all stream data is sent to the server at the time of query execution. However, the driver also provides functionality that allows up to 8KB of stream data to be sent to the server at a time. For more information, see the Sending Images to the Server (SQLSRV) section below or How to: Send Data as a Stream in the product documentation. For more information about sending data to the server, see Updating Data in the product documentation.
12
For more information, see How to: Specify PHP Data Types and How to: Specify SQL Server Data Types in the product documentation. The $options parameter is used when calling sqlsrv_prepare. The default behavior is to send all stream data to the server at the time of query execution. However, data can be sent to the server in chunks up to 8KB in size by setting "SendStreamParamsAtExec" to 0 in the $options parameter. When this is done, calls to sqlsrv_send_stream data (after query execution) are required to send stream data to the server (see next bullet). For more information, sqlsrv_send_stream_data see in the product documentation.
13
14
that indicates whether it is the procedural or PDO driver (sqlsrv or pdo), whether it is compatible with PHP 5.3 or PHP 5.2 (53 or 52), whether it thread-safe or non-threadsafe (ts or nts), and which compiler the driver was compiled with (vc6 or vc9). For example, the php_pdo_sqlsrv_53_nts_vc9.dll file is the PDO driver, is compatible with PHP 5.3, is non-thread-safe, and was compiled with Visual C++ 9 (vc9) compiler. Note that the recommended way to run PHP with Internet Information Services is to use the FastCGI module and a non-thread-safe version of PHP (and therefore a nonthread-safe version of the PDO driver). Whether you choose a vc6 or vc9 version of the driver will depend on the compiler that your version of PHP was compiled with. For more information about which .dll file you should use, see System Requirements. Loading the PDO driver is similar to loading any PHP extension: 1. Put the driver file in your PHP extension directory. 2. Modify the php.ini file to include the extension. For example: extension=php_pdo_sqlsrv_53_nts_vc9.dll See Figure 1 (PDO) below for more detail. 3. Restart the Web server. For more information, see Loading the Driver in the product documentation.
15
Figure 1 (PDO): The Dynamic Extensions section of the php.ini. One way to be sure that the driver is loaded and to see the configuration settings is to run a script that calls the phpinfo() function. To do this, follow these steps: 5. Open a text file and copy the following code into it: <?php phpinfo(); ?> 6. Save the file as info.php in your Web servers root directory. 7. Open a browser and go to http://localhost/info.php. 8. Scroll down the resulting page to find the sqlsrv section. The following figure shows the pdo_sqlsrv section of the phpinfo() page. This output confirms the driver is loaded and the configuration settings are set to default values.
16
the product documentation) establishes a connection to the local instance of SQL Server Express and specifies the AdventureWorks database as the database in use: $serverName = "(local)\sqlexpress"; try { $conn = new PDO("sqlsrv:server=$serverName;Database=AdventureWorks", "", ""); $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); } catch(Exception $e) { die( print_r( $e->getMessage() ) ); }
The code above establishes a connection using Windows Authentication by passing empty strings for the $username and $password parameters. In most scenarios, this means that the Web server's process identity or thread identity (if the Web server is using impersonation) is used to connect to the server, not an end-user's identity. The PDO::__construct function accepts four parameters: $dsn, $username (optional), $password (optional), and $driverOptions (optional). $dsn This required parameter is a string that contains the prefix name (always sqlsrv), a colon, and the server keyword. For example, "sqlsrv:server=(local)\sqlexpress". You can optionally specify other connection keywords. (See Connection Options for a description of the server keyword and the other connection keywords.) The entire $dsn parameter is in quotation marks, so each connection keyword should not be individually quoted. $username - This optional parameter is a string that contains the user's login name. To connect using SQL Server Authentication, specify the login ID. To connect using Windows Authentication, specify "". $password This optional parameter is a string that contains the user's password. To connect using SQL Server Authentication, specify the password. To connect using Windows Authentication, specify "". $driverOptions This optional parameter is used to specify PDO Driver Manager attributes, and SQL Server Driver for PHP specific driver attributes -PDO::SQLSRV_ATTR_ENCODING and PDO::SQLSRV_ATTR_DIRECT_QUERY. An invalid attribute will not generate an exception. Invalid attributes generate exceptions when specified with PDO::setAttribute.
17
For more information about creating a connection, see the Connection Pooling (SQLSRV and PDO) section later in this paper and Connecting to the Server in the product documentation.
The following code (from the Example Application (PDO Extension) in the product documentation) demonstrates the use of the PDO::prepare and PDOStatement::execute methods: $params = array($_POST['query']); $tsql = "SELECT ProductID, Name, Color, Size, ListPrice FROM Production.Product WHERE Name LIKE '%' + ? + '%' AND ListPrice > 0.0"; $getProducts = $conn->prepare($tsql); $getProducts->execute($params); The PDO::prepare method accepts two parameters: $tsql and $options (optional). $tsql This required parameter is a string that defines a Transact-SQL query. Question marks (?) or named parameters (prefixed with a colon) are used as placeholders for parameters. $params This optional parameter is an array of key-value pairs that allow you to set options on the query. The possible keys are PDO::ATTR_CURSOR, PDO::SQLSRV_ATTR_ENCODING, PDO::SQLSRV_ATTR_DIRECT_QUERY, and PDO::SQLSRV_ATTR_QUERY_TIMEOUT. For information about the possible corresponding values, see PDO::prepare.
Microsoft Corporation 2010
18
The PDOStatement::execute method accepts one optional parameter: $params. $params: This optional parameter is an associative array that contains the values of parameters in the query that is being executed. If question marks (?) are used as parameter placeholders in the query, the $params array is simply an array of parameter values. If named paramerters are used in the query, the $params array is an array of key-value pairs where each key is the name used as the placeholder and the value is the parameter value. See PDO::prepare for examples of each type of usage.
Note The PDO driver supports both question marks (?) and named parameters (:paramName) as placeholders for parameter values. For an example that demonstrates the use of named parameters, see PDO::prepare.
For more information about retrieving data, see Retrieving Data in the product documentation.
19
EndProductsTable(); } The PDOStatement::fetchAll method accepts three parameters - $fetch_style, $column_index (optional), and $ctor_args (optional): The $fetch_style parameter (optional) is a constant specifying the format of the row data. See PDOStatement::fetch for a complete list of values. The $column_index parameter (optional) is an integer value representing the column to return if $fetch_style is PDO::FETCH_COLUMN. Zero (0) is the default. The $ctor_args parameter (optional) is an array of the parameters for a class constructor when $fetch_style is PDO::FETCH_CLASS or PDO::FETCH_OBJ.
20
Note The PDO driver supports both question marks (?) and named parameters (:paramName) as placeholders for parameter values. For an example that demonstrates the use of named parameters, see PDO::prepare. The PDOStatement::bindColumn method takes five parameters - $column, $param, $type (optional), $maxLen (optional), and $driverdata (optional): The $column parameter specifies the number of the column (1-based index) or name of the column in the result set. The $param specifies the name of the PHP variable to which the column will be bound. The $type parameter (optional) specifies the data type of the parameter, represented by a PDO::PARAM_* constant. The $maxLen parameter (optional) is not used by this PDO implementation. The $driverdata parameter (optional) is used to specify driver-specific data. For example, you could specify PDO::SQLSRV_ENCODING_UTF8 to bind the column to a variable as a string encoded in UTF-8.
The PDOStatement::fetch method takes three parameters - $fetch_style (optional), $cursor_orientation (optional), and $cursor_offset (optional): The $fetch_style parameter (optional) is a constant that specifies the format of the returned data. See PDOStatement::fetch for a complete list of possible values. The $cursor_orientation parameter (optional) is a constant that specifies the row to retrieve when the prepare statement specifies PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL. See PDOStatement::fetch for a complete list of possible values. The $cursor_offset parameter (optional) specifies the row to fetch when $cursor_orientation is either PDO::FETCH_ORI_ABS or PDO::FETCH_ORI_REL and PDO::ATTR_CURSOR is PDO::CURSOR_SCROLL.
21
date("Y-m-d"), &$_POST['email'], &$_POST['rating'], &$_POST['comments']); $insertReview = $conn->prepare($tsql); $insertReview->execute($params); Note The PDO driver supports both question marks (?) and named parameters (:paramName) as placeholders for parameter values. For an example that demonstrates the use of named parameters, see PDO::prepare. For more information about sending data to the server, see Updating Data in the product documentation.
22
The $parameter parameter is a parameter identifier. For a statement using named placeholders, a parameter name (:name). For a prepared statement using the question mark syntax, this will be the 1-based index of the parameter. The $variable parameter is the name of the PHP variable to bind to the SQL statement parameter. The $data_type parameter (optional) is a PDO::PARAM_* constant. The default is PDO::PARAM_STR. The $length parameter (optional) is the length of the data type. You can specify SQLSRV_PARAM_OUT_DEFAULT_SIZE to indicate the default size when using PDO::PARAM_INT or PDO::PARAM_BOOL in $data_type. The $driver_options parameter (optional) specifies driver-specific options. For example, you could specify PDO::SQLSRV_ENCODING_UTF8 to bind the column to a variable as a string encoded in UTF-8.
23
Note The first time you execute a query on a connection that was retrieved from a pool, the driver tells the server to reset the connection prior to executing the query. Resetting the connection returns the connection to its original state. For example, resetting the connection deletes any temporary objects and rolls back any pending transactions.
24
} This code demonstrates how to connect to SQL Azure using the PDO driver: $serverName = "tcp:ServerID.database.windows.net, 1433"; try { $conn = new PDO("sqlsrv:server=$serverName;Database=DBName", "User@ServerID", "Password"); $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); } catch(Exception $e) { die( print_r( $e->getMessage() ) ); } Once the connection code has been changed, the remaining application code may require some changes. For more information, see Getting Started with PHP and SQL Azure.
Resources
The following resources are available for developing applications with the SQL Server 2005 Driver for PHP: Download site: SQL Server 2005 Driver for PHP in the Microsoft Download Center Peer-to-peer support: SQL Server Driver for PHP in the MSDN Forums Online documentation: SQL Server 2005 Driver for PHP Documentation in MSDN Library Source code: Microsoft SQL Server 2005 Driver for PHP in CodePlex IIS site for PHP on Windows PHP-related projects on CodePlex.com Blogs: o o o o o o SQL Server Driver for PHP Team Blog The Interoperability Team Blog Ruslan Yakushevs Blog Josh Holmes Blog Kanwaljeet Singlas Blog Zach Owens Blog
Microsoft Corporation 2010
25
Conclusion
The SQL Server Driver for PHP provides fast and reliable access to SQL Server data using PHP. The driver leverages both Microsoft and PHP technologies (such as Windows Authentication, ODBC connection pooling, and PHP streams) to enable the development of rich PHP Web applications. For more information: SQL Server Web site: http://www.microsoft.com/sqlserver/ SQL Server TechCenter: http://technet.microsoft.com/en-us/sqlserver/ SQL Server DevCenter: http://msdn.microsoft.com/en-us/sqlserver/ Data Platform DevCenter: http://msdn.microsoft.com/en-us/data/
Did this paper help you? Please give us your feedback. Tell us on a scale of 1 (poor) to 5 (excellent), how would you rate this paper and why have you given it this rating? For example: Are you rating it high due to having good examples, excellent screen shots, clear writing, or another reason? Are you rating it low due to poor examples, fuzzy screen shots, or unclear writing?
This feedback will help us improve the quality of white papers we release. Send feedback.