The SQLSRV driver is a Microsoft supported PHP extension that allows you to access Microsoft SQL Server and SQL Azure databases. It is an alternative for the MSSQL drivers that were deprecated as of PHP 5.3, and have been removed from PHP 7.
The SQLSRV extension can be used on the following operating systems:
- Windows Vista Service Pack 2 or later
- Windows Server 2008 Service Pack 2 or later
- Windows Server 2008 R2
- Windows 7
The SQLSRV extension requires that the Microsoft SQL Server 2012 Native Client be installed on the same computer that is running PHP. If the Microsoft SQL Server 2012 Native Client is not already installed, click the appropriate link at the "Requirements" documentation page.
To download the latest SQLSRV drivers, go to the following: Download
A full list of system requirements for the SQLSRV Drivers can be found here: System Requirements
Those using SQLSRV 3.1+ must download the Microsoft ODBC Driver 11 for SQL Server
PHP7 users can download the latest drivers from GitHub
Microsoft® ODBC Driver 13 for SQL Server supports Microsoft SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Server 2014, SQL Server 2016 (Preview), Analytics Platform System, Azure SQL Database and Azure SQL Data Warehouse.
Creating a Connection
SQLSRV also has a PDO Driver. To connect using PDO:
Fetching Query Results
There are 3 main ways to fetch results from a query:
sqlsrv_fetch_array() retrieves the next row as an array.
sqlsrv_fetch_array() has an optional second parameter to fetch back different types of array:
SQLSRV_FETCH_BOTH(default) can be used; each returns the associative, numeric, or associative and numeric arrays, respectively.
sqlsrv_fetch_object() retrieves the next row as an object.
sqlsrv_fetch() makes the next row available for reading.
Invoking a Stored Procedure
To call a stored procedure on the server:
Making a Parameterised Query
If you plan on using the same query statement more than once, with different parameters, the same can be achieved with the
sqlsrv_execute() functions, as shown below:
Making a Simple Query
Note: the use of square brackets
 is to escape the word
table as it is a reserved word. These work in the same way as backticks
` do in MySQL.
Retrieving Error Messages
When a query goes wrong, it is important to fetch the error message(s) returned by the driver to identify the cause of the problem. The syntax is:
This returns an array with:
|SQLSTATE||The state that the SQL Server / OBDC Driver is in|
|code||The SQL Server error code|
|message||The description of the error|
It is common to use the above function like so: