建立SQL伺服器連結以Windows SQL Server 2008 R2為例
Construct the SQL Server Connection(Windows SQL Server 2008 R2)
前言:
有別於過去撰寫簡易的個人網頁,在企業內通常會有多台伺服器,專責處理不同的資料。因此當需要利用網頁伺服器(此處以Windows的IIS搭配php語法撰寫)撈取資料時候,就必須要先建立連結伺服器才能達成。
在正文當中會簡單的以示意圖說明,進行連結的伺服器,最後則以php測試是否有連接成功。
正文:
下圖繪製的為此案例的示意圖,總共有兩台機器,其中一台機器同時為網頁伺服器與資料庫伺服器(但不進行資料處理);另一台機器則為資料庫伺服器,負責處理與儲存資料。而今天我們需要透過網頁伺服器撈取資料並達到即時撈取資料則需要兩台資料庫伺服器之間有所連接才能以php撰寫SQL去撈取資料並輸出。
![]() |
案例示意圖
|
而為了方便讀者快速了解處理方式在示意圖下方也標註了以下的處理步驟:
1)於資料提供的伺服器,開啟Microsoft SQL Server Management Studio
2)登入後,進入安全性/登入中,更改sa設定的帳號密碼(若忘記密碼)
3)於網頁伺服器所在的機器中,開啟Microsoft SQL Server Management Studio並登入
4)於伺服器物件下,連接的伺服器中,進行新增連接伺服器
5)輸入伺服器相關的資料,伺服器名稱與對應的認證帳戶
注意此處的第二步驟,除非必要才要進行,因為可能會影響到現存的資料庫連線(因為密碼被修改過去建立的連結需要更新成新密碼才能使用),其他影響還有與資料庫連線相關的工作,如在排程的工作也會因為連線錯誤而失敗。
新增連接伺服器 |
輸入認證帳戶 |
PHP測試資料庫連接
資料庫連接測試的語法如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$conn = mssql_connect("Localhost SQL Server Name", "sa", "Password"); | |
//select the database table and check if it exists or not | |
if($conn){ | |
echo '連接伺服器成功(Connection success)<br>'; | |
}else{ | |
echo '連接伺服器失敗(Connection fail)<br>'; | |
} | |
//The below two lines is help to remove the error message | |
$result = mssql_query("SET ANSI_NULLS ON") or die(mssql_get_last_message()); | |
$result = mssql_query("SET ANSI_WARNINGS ON") or die(mssql_get_last_message()); | |
//The query fot searching the specific database table | |
$result=mssql_query( | |
'SELECT TOP 10 [ID] | |
,[UserName] | |
,[ClientIP] | |
,[Datetime] | |
,[Action] | |
,[Detail] | |
FROM [192.168.3.161].[SOMAC].[dbo].[Systemlog] | |
'); | |
//query some data from the connected server database table | |
$total_fields=mssql_num_fields($result); | |
$total_rows=mssql_num_rows($result); | |
echo '資料欄位數(The number of the fields): '.$total_fields.'<br>'; | |
echo '資料列數(The number of the rows): '.$total_rows.'<br>'; | |
?> |
注意此處一樣是連結網頁伺服器主機內的資料庫伺服器,而透過撈取系統內建的資料表作為測試。
結果如下:
測試結果 |
留言
張貼留言