PHP串連MSSQL2008/2005資料庫與以往的串連mssql2000是不一樣的,串連mssql2008/2005是需要自己添加PHP對MSSQL串連的驅動擴充了,而我們常用的hp.ini中的extension=php_mssql.dll擴充只適用串連於MSSQL2000,下面我們就來看看對此的解決辦法。
1.下載擴充
(1)去官方下載一個SQL Server Driver for PHP的擴充包,我是在這裡下載的http://www.microsoft.com/en-us/download/details.aspx?id=20098【記得下載後好像是要先安裝然後再解壓】
(2)您也可以直接從本站下載(我之前下載的,來源於microsoft官方)【點擊此處直接下載】
將下載下來的rar檔案解壓後你就會得到一堆的.dll檔案
下載驅動程式,下載後安裝釋放程式,裡面有以下檔案:
php_pdo_sqlsrv_52_nts.dll
php_pdo_sqlsrv_52_ts.dll
php_pdo_sqlsrv_53_nts_vc6.dll
php_pdo_sqlsrv_53_nts_vc9.dll
php_pdo_sqlsrv_53_ts_vc6.dll
php_pdo_sqlsrv_53_ts_vc9.dll
php_sqlsrv_52_nts.dll
php_sqlsrv_52_ts.dll
php_sqlsrv_53_nts_vc6.dll
php_sqlsrv_53_nts_vc9.dll
php_sqlsrv_53_ts_vc6.dll
php_sqlsrv_53_ts_vc9.dll
SQLServerDriverForPHP.chm(手冊,英文夠好的話,可以看看,嘿嘿)
SQLServerDriverForPHP_License.rtf
SQLServerDriverForPHP_Readme.htm(讀我檔案)
2.添加擴充
根據(vc6/vc9)需要選擇擴充,我的環境是WAMP(php5.2.6/apache2.2.8),我選用的是php_sqlsrv_52_ts_vc6.dll,php_pdo_sqlsrv_52_ts_vc6.dll這兩個檔案,複製到wamp安裝目錄下的ext目錄下,我的ext目錄是在wamp/bin/php/php5.2.6/ext/
3.配置php.ini
(1)在php.ini的Dynamic Extensions中添加如下兩條擴充:
extension=php_sqlsrv_52_ts_vc6.dll
extension=php_pdo_sqlsrv_52_ts_vc6.dll
(2)將;extension=php_pdo.dll前面的;去掉,開啟pdo串連擴充
(3)重新啟動apache
4.串連資料庫(pdo串連)
<?php $servern="SFKFK27EL8FJ\SQLTRY"; $coninfo=array("Database"=>"try2","UID"=>"sa","PWD"=>"123"); $conn=sqlsrv_connect($servern,$coninfo) or die ("串連失敗!"); $val=sqlsrv_query($conn,"select * from usertable"); while($row=sqlsrv_fetch_array($val)){ echo $row[1]."<br />"; } sqlsrv_close($conn); ?>
5.例子
連結樣本:
mssql_lib.php檔案如下:
<?phpclass DB { var $con = null; function __construct($dbhost,$dbuser,$dbpass,$dbname) { $connectionInfo = array("UID"=>$dbuser,"PWD"=>$dbpass,"Database"=>$dbname); $this->con = sqlsrv_connect($dbhost,$connectionInfo); } function query($sql){ $result = sqlsrv_query($this->con, $sql); } function getRow($sql){ $result = sqlsrv_query($this->con, $sql); $arr = array(); while($row = sqlsrv_fetch_array($result)) { $arr[] = $row; } return $arr[0]; } function getAll($sql){ $result = sqlsrv_query($this->con, $sql); $arr = array(); while($row = sqlsrv_fetch_array($result)) { $arr[] = $row; } return $arr; } function __destruct() { unset($con); }}
test.php頁面如下:
//簡單調用$db = new DB(DB_HOST, DB_USER, DB_PASS, DB_NAME);$sql = "select * from crm_order_batch where (status=0 or status is null) and lock_id is not null ";$orders_add_list = $db->getAll($sql);