在 PHP 中连接 SQL Server 分为以下步骤:加载 SQL Server 驱动程序创建连接字符串,包含服务器名称、数据库、用户名和密码建立连接验证连接是否成功执行查询或命令处理结果关闭连接

如何使用 PHP 连接 SQL Server
简介
在 PHP 中连接 SQL Server 涉及几个步骤,包括:
步骤 1:加载 SQL Server 驱动程序
立即学习“PHP免费学习笔记(深入)”;
<code class="php">// 使用 sqlsrv 扩展 extension=php_sqlsrv.dll</code>
步骤 2:创建连接字符串
<code class="php">$serverName = "your-server-name";
$connectionInfo = array("Database"=>"your-database", "UID"=>"username", "PWD"=>"password");</code>步骤 3:建立连接
<code class="php">$conn = sqlsrv_connect($serverName, $connectionInfo);</code>
步骤 4:验证连接
<code class="php">if (!$conn) {
die(print_r(sqlsrv_errors(), true));
}</code>步骤 5:执行查询或命令
<code class="php">$query = "SELECT * FROM your-table";
$stmt = sqlsrv_query($conn, $query);
if (!$stmt) {
die(print_r(sqlsrv_errors(), true));
}</code>步骤 6:处理结果
<code class="php">while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
// 处理每一行数据
print_r($row);
}</code>步骤 7:关闭连接
<code class="php">sqlsrv_close($conn);</code>
示例代码
<code class="php">// 加载 SQL Server 驱动程序
extension=php_sqlsrv.dll
// 创建连接字符串
$serverName = "localhost";
$connectionInfo = array("Database"=>"MyDatabase", "UID"=>"sa", "PWD"=>"your-password");
// 建立连接
$conn = sqlsrv_connect($serverName, $connectionInfo);
if (!$conn) {
die(print_r(sqlsrv_errors(), true));
}
// 执行查询
$query = "SELECT * FROM MyTable";
$stmt = sqlsrv_query($conn, $query);
if (!$stmt) {
die(print_r(sqlsrv_errors(), true));
}
// 处理结果
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
print_r($row);
}
// 关闭连接
sqlsrv_close($conn);</code>以上就是php如何连接sqlserver的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号