Last updated: August 26, 2026.
Use Microsoft’s PDO_SQLSRV driver with the Microsoft ODBC Driver for SQL Server. Keep credentials in environment-backed configuration and enable exception mode.
Connect and query safely
<?php
declare(strict_types=1);
$pdo = new PDO(
'sqlsrv:Server=tcp:sql.example.com,1433;Database=ApplicationDb;Encrypt=yes;TrustServerCertificate=no',
getenv('SQLSERVER_USER'),
getenv('SQLSERVER_PASSWORD'),
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
$statement = $pdo->prepare(
'SELECT customer_name FROM customers WHERE customer_id = :customer_id'
);
$statement->execute(['customer_id' => 42]);
$customer = $statement->fetch(PDO::FETCH_ASSOC);Install compatible versions of the Microsoft PHP driver and ODBC driver, verify the extension is loaded, and validate the server certificate. See Microsoft’s PHP driver documentation.
Building a SQL Server web application? PHPRunner can generate data-entry, reporting, and administration pages.