PHP 数据库

php如何连接sqlserver数据库

小亿
272
2024-01-31 10:26:44
栏目: 云计算

在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);
?>

请注意替换代码中的serverNamedbNameusernamepasswordtableNamecolumn1column2为实际的数据库连接信息和查询语句所需的参数。

0
看了该问题的人还看了