sqlsrv_connect

下載 PHP 驅動程式

建立連接資源,並開啟連接。 依預設會使用 Windows 驗證來嘗試連接。

語法

  
sqlsrv_connect( string $serverName [, array $connectionInfo])  

參數

$serverName:一個字串,指定要建立連接之伺服器的名稱。 執行個體名稱 (例如 "myServer\instanceName") 或通訊埠編號 (例如 "myServer, 1521") 可以納入為此字串的一部分。 如需此參數之可用選項的完整描述,請參閱搭配 SQL Native Client 使用連接字串關鍵字的<ODBC 驅動程式連接字串關鍵字>一節中的<Server 關鍵字>。

從 Microsoft Drivers for PHP for SQL Server 3.0 版開始,您也可以使用 "(localdb)\instancename" 來指定 LocalDB 執行個體。 如需詳細資訊,請參閱支援 LocalDB

此外,從 Microsoft Drivers for PHP for SQL Server 3.0 版開始,您也可以指定虛擬網路名稱,以連線至 Always On 可用性群組。 如需 Microsoft Drivers for PHP for SQL Server 的 Always On 可用性群組支援詳細資訊,請參閱高可用性與災害復原的支援

$connectionInfo [選用]:一個關聯陣列,其中包含連線屬性 (例如 array("Database" => "AdventureWorks"))。 如需支援陣列的索引鍵清單,請參閱 Connection Options

傳回值

PHP 連接資源。 如果連接無法成功建立並開啟,則傳回 false

備註

如果未在選用 $connectionInfo 參數中指定 UIDPWD 索引鍵的值,則會使用 Windows 驗證嘗試進行連接。 如需關於連接到伺服器的詳細資訊,請參閱如何:使用 Windows 驗證進行連線以及如何:使用 SQL Server 驗證進行連線

範例

下列範例會使用 Windows 驗證建立及開啟連接。 此範例假設本機電腦上已安裝 SQL Server 和 AdventureWorks 資料庫。 從命令列執行範例時,所有輸出都會寫入至主控台。

<?php  
/*  
Connect to the local server using Windows Authentication and specify  
the AdventureWorks database as the database in use. To connect using  
SQL Server Authentication, set values for the "UID" and "PWD"  
 attributes in the $connectionInfo parameter. For example:  
$connectionInfo = array("UID" => $uid, "PWD" => $pwd, "Database"=>"AdventureWorks");  
*/  
$serverName = "(local)";  
$connectionInfo = array( "Database"=>"AdventureWorks");  
$conn = sqlsrv_connect( $serverName, $connectionInfo);  
  
if( $conn )  
{  
     echo "Connection established.\n";  
}  
else  
{  
     echo "Connection could not be established.\n";  
     die( print_r( sqlsrv_errors(), true));  
}  
  
//-----------------------------------------------  
// Perform operations with connection.  
//-----------------------------------------------  
  
/* Close the connection. */  
sqlsrv_close( $conn);  
?>  

另請參閱

SQLSRV 驅動程式 API 參考

連線到伺服器

關於文件中的程式碼範例