<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "=== SQL Server 连接测试 ===\n\n";

// 测试1：直接使用 sqlsrv_connect
echo "测试1: 使用 sqlsrv_connect\n";
$serverName = "192.168.0.156\dlsql";
$connectionInfo = array(
    "Database" => "ywsj",
    "UID" => "yisheng",
    "PWD" => "yisheng"
);

$conn = sqlsrv_connect($serverName, $connectionInfo);

if ($conn) {
    echo "✅ 连接成功！\n";
    
    // 测试查询
    $sql = "SELECT 1 AS test";
    $stmt = sqlsrv_query($conn, $sql);
    if ($stmt) {
        $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
        echo "✅ 查询成功: " . $row['test'] . "\n";
    } else {
        echo "❌ 查询失败: " . print_r(sqlsrv_errors(), true) . "\n";
    }
    
    sqlsrv_close($conn);
} else {
    echo "❌ 连接失败\n";
    $errors = sqlsrv_errors();
    if ($errors) {
        foreach ($errors as $error) {
            echo "SQLSTATE: " . $error['SQLSTATE'] . "\n";
            echo "代码: " . $error['code'] . "\n";
            echo "消息: " . $error['message'] . "\n";
        }
    }
}

echo "\n";

// 测试2：使用不同的连接格式
echo "测试2: 使用 IP,端口 格式\n";
$serverName2 = "192.168.0.156,1433";
$conn2 = sqlsrv_connect($serverName2, $connectionInfo);

if ($conn2) {
    echo "✅ 连接成功！\n";
    sqlsrv_close($conn2);
} else {
    echo "❌ 连接失败\n";
    $errors = sqlsrv_errors();
    if ($errors) {
        foreach ($errors as $error) {
            echo "消息: " . $error['message'] . "\n";
        }
    }
}

echo "\n";

// 测试3：检查扩展是否加载
echo "测试3: 检查扩展加载情况\n";
if (extension_loaded('sqlsrv')) {
    echo "✅ sqlsrv 扩展已加载\n";
} else {
    echo "❌ sqlsrv 扩展未加载\n";
}

if (extension_loaded('pdo_sqlsrv')) {
    echo "✅ pdo_sqlsrv 扩展已加载\n";
} else {
    echo "❌ pdo_sqlsrv 扩展未加载\n";
}

echo "\n=== 测试结束 ===";
?>