在PHP中連接SQL Server數據庫,可以使用PDO(PHP數據對象)或者SQLSRV擴展。
方法一:使用PDO擴展連接SQL Server數據庫
<?php
$serverName = "serverName";
$connectionOptions = array(
"Database" => "dbName",
"Uid" => "username",
"PWD" => "password"
);
// 建立連接
$conn = new PDO("sqlsrv:server=$serverName;Database=dbName", "username", "password");
// 設置錯誤處理模式為異常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// 執行SQL查詢
$stmt = $conn->query("SELECT * FROM tableName");
// 獲取查詢結果
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['column1'] . ", " . $row['column2'] . "<br/>";
}
// 關閉連接
$conn = null;
?>
方法二:使用SQLSRV擴展連接SQL Server數據庫
<?php
$serverName = "serverName";
$connectionOptions = array(
"Database" => "dbName",
"Uid" => "username",
"PWD" => "password"
);
// 建立連接
$conn = sqlsrv_connect($serverName, $connectionOptions);
if ($conn === false) {
die(print_r(sqlsrv_errors(), true));
}
// 執行SQL查詢
$query = "SELECT * FROM tableName";
$stmt = sqlsrv_query($conn, $query);
if ($stmt === false) {
die(print_r(sqlsrv_errors(), true));
}
// 獲取查詢結果
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo $row['column1'] . ", " . $row['column2'] . "<br/>";
}
// 關閉連接
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
?>
請注意替換代碼中的serverName
、dbName
、username
、password
、tableName
、column1
和column2
為實際的數據庫連接信息和查詢語句所需的參數。