Connect to SQL Server through PDO using SQL Server Driver

Here is an example of how to connect to a SQL Server database using PDO and the SQL Server driver:

<?php

$serverName = "serverName\sqlexpress";
$connectionInfo = ["Database" => "dbName", "UID" => "username", "PWD" => "password"];
$conn = sqlsrv_connect($serverName, $connectionInfo);

This example assumes that you have the SQL Server driver for PDO installed and configured on your system. If you don't have the driver installed, you can download it from the Microsoft website.

Watch a course Learn object oriented PHP

Once the connection is established, you can use PDO's methods, such as query() and prepare(), to execute SQL statements and retrieve data from the database.

<?php

$stmt = $conn->query('SELECT * FROM mytable');
while ($row = $stmt->fetch()) {
    print_r($row);
}

You can also use prepared statements to protect against SQL injection attacks.

<?php

$stmt = $conn->prepare('SELECT * FROM mytable WHERE id = :id');
$stmt->execute(['id' => $id]);
while ($row = $stmt->fetch()) {
    print_r($row);
}