Conect to SQL Server DB
Posted: Mon Sep 14, 2026 10:18 am
Code: Select all
<?php
// add extension=pdo_sqlsrv (pdo_sqlsrv_74_nts.dll for PHP 7.4.33)
// Download ODBC Drivers for SQL Server
// https://learn.microsoft.com/en-us/sql/connect/odbc/download-odbc-driver-for-sql-server?view=sql-server-ver17
$serverName = "[SQL SERVER],1433"; // Server name or IP, optionally with port
$database = "[DB NAME]";
$username = "[USERNAME]";
$password = "[PASSWORD]";
try {
// Configure the Data Source Name (DSN)
$dsn = "sqlsrv:Server=$serverName;Database=$database";
// Create the PDO connection object
$conn = new PDO($dsn, $username, $password);
// Set error handling mode to exceptions
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully using PDO!";
// 3. Prepare and execute the SQL query
$sql = "SELECT * FROM dimensions;";
$stmt = $conn->query($sql);
// $stmt->execute();
// 4. Fetch and display the results
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "ID: " . $row['id'] . " - Part Number: " . $row['part_number'] . "\r\n";
}
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
?>