Skip to content

Instantly share code, notes, and snippets.

@MCF
Last active July 24, 2023 03:05
Show Gist options
  • Save MCF/1a03d45f113d49d74e12 to your computer and use it in GitHub Desktop.
Save MCF/1a03d45f113d49d74e12 to your computer and use it in GitHub Desktop.
PDO sqlsrv PHP driver, connect and query SQL Server database - reduced test case.
<?php
$serverName = "sqlserver.example.com";
$database = "myDbName";
$uid = 'sqlserver_username';
$pwd = 'password';
try {
$conn = new PDO(
"sqlsrv:server=$serverName;Database=$database",
$uid,
$pwd,
array(
//PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
}
catch(PDOException $e) {
die("Error connecting to SQL Server: " . $e->getMessage());
}
echo "<p>Connected to SQL Server</p>\n";
echo "<p>PDO::ATTR_PERSISTENT value:</p>\n";
echo "<pre>";
echo var_export($conn->getAttribute(PDO::ATTR_PERSISTENT), true);
echo "</pre>";
echo "<p>PDO::ATTR_DRIVER_NAME value:</p>\n";
echo "<pre>";
echo var_export($conn->getAttribute(PDO::ATTR_DRIVER_NAME), true);
echo "</pre>";
echo "<p>PDO::ATTR_CLIENT_VERSION value:</p>\n";
echo "<pre>";
echo var_export($conn->getAttribute(PDO::ATTR_CLIENT_VERSION), true);
echo "</pre>";
$query = 'select top 5 * from tbl_users';
$stmt = $conn->query( $query );
echo "<pre>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
print_r($row);
}
echo "</pre>";
// Free statement and connection resources.
$stmt = null;
$conn = null;
?>
@diogenesjup
Copy link

Nice Work!! Great

@tossapolch
Copy link

Thank you very much. I have never used sql server with PHP. The data display in the database is very confusing. I usually use phpMyAdmin with php, it's not confusing.

@nesmamagdy
Copy link

THX

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment