阅读量:0
在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
为实际的数据库连接信息和查询语句所需的参数。