PHP与MSSQL数据库的链接方法

发布时间:2025-12-10 12:48:30 浏览次数:10

PHP与MSSQL的链接是非常重要的,本文将介绍怎样使用PHP与MSSQL数据库进行链接。

1. 首先,一定要在服务器上安装MSSQL服务器,和Microsoft SQL Native Client,以便完成MSSQL和PHP之间的连接。

2. 在PHP中添加mssql模块。可使用以下PHP代码来到达此目的:

“`PHP

//添加mssql模块

php_extension_mssql( );

?>


3. 在页面最前面定义MSSQL服务器连接字符串:

```PHP

$serverName = "localhost";
$connectionOptions = array( "Database"=>"myDatabase",
"Uid"=>"myUsername", "PWD"=>"myPassword" );

//Establish the connection
$conn = sqlsrv_connect($serverName, $connectionOptions);
if($conn === false)
{
die(print_r(sqlsrv_errors()));
}
?>

4. 履行MSSQL查询

在MSSQL服务器之间建立了连接以后,可使用下面的PHP代码进行MSSQL查询:

“`PHP

//uncomment once connection is established

$tsql= “SELECT Name, Location FROM Employees”;

$getResults= sqlsrv_query($conn, $tsql);

//Uncomment when expecting multiple rows

echo (“Reading data from the table

“);

while ($row = sqlsrv_fetch_array($getResults, SQLSRV_FETCH_ASSOC)) {

echo ($row[‘Name’] . ” ” . $row[‘Location’] . “
“);

}

?>


最后,要关闭MSSQL连接,可使用以下PHP代码:

```PHP

// Close the connection.
sqlsrv_close( $conn);
?>

需要做网站?需要网络推广?欢迎咨询客户经理 13272073477