PHP SQL Server Connection Guide
In PHP, you can connect to a SQL Server database using either PDO (PHP Data Objects) or the SQLSRV extension.
Option 1: Connect to a SQL Server database using the PDO extension.
<?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;
?>
Option 1: Method Two: Connect to SQL Server database using the SQLSRV extension.
<?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);
?>
Please make sure to replace serverName, dbName, username, password, tableName, column1, and column2 in the code with the actual database connection information and parameters needed for the query.