建立連接資源,並開啟連接。 依預設會使用 Windows 驗證來嘗試連接。
語法
sqlsrv_connect( string $serverName [, array $connectionInfo])
參數
$serverName:一個字串,用來指定正在建立連線的伺服器名稱。 實例名稱(例如 <server>\instanceName)或埠號(例如 <server>, 1521)可以作為此字串的一部分加入。 欲了解此參數可用選項的完整說明,請參閱 ServerDSN 中的關鍵字及連接字串關鍵字與屬性。
從 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 參數中指定 UID 和 PWD 索引鍵的值,則會使用 Windows 驗證嘗試進行連接。 有關連線至伺服器的更多資訊,請參閱 SQL Server 與 Windows 驗證。
範例
下列範例會使用 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);
?>