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:
Here is an example of how to connect to a SQL Server database using PDO and the pdo_sqlsrv driver:
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"];
$dsn = "sqlsrv:Server=$serverName;Database={$connectionInfo['Database']}";
$conn = new PDO($dsn, $connectionInfo['UID'], $connectionInfo['PWD']);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);This example assumes that you have the pdo_sqlsrv driver installed and configured on your system. If you don't have the driver installed, you can download it from the Microsoft website.
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.
Example of using PDO's methods, once the connection is established in PHP
<?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.
Example of using prepared statements to protect against SQL injection attacks in PHP
<?php
$stmt = $conn->prepare('SELECT * FROM mytable WHERE id = :id');
$stmt->execute(['id' => $id]);
while ($row = $stmt->fetch()) {
print_r($row);
}