PHP连接MSSQL的PDO ODBC方法及常见问题排查
在PHP环境中,通常仅存在php_pdo_odbc.dll这一扩展文件。
因此,目前推荐且较为完善的PHP连接MSSQL的方式如下所示。
具体实现代码如下:
<?php
$cnx = new PDO("odbc:Driver={SQL Server};Server=127.0.0.1;Database=test;",'sa','asd123');
var_dump($cnx);
$a = $cnx->query("SELECT * FROM [user]");
var_dump($a);
foreach ($a as $b) {
var_dump($b);
}
?> 关于PHP无法连接MSSQL数据库的问题
今日在新配置的IIS+PHP服务器上运行时,发现PHP连接远程MSSQL数据库出现错误,相关出错代码如下:
Warning: mssql_connect(): Unable to connect to server:
此前该配置一直正常,此次故障令人困惑。经网络搜索相关文章后得知,服务器需安装MSSQL组件才能支持PHP连接MSSQL。尽管新服务器原本无需此组件,但为解决问题只能进行安装,安装完成后连接恢复正常。
不禁思考,若在Linux系统的Apache+PHP环境下是否也会遇到相同情况?想必不需要安装MSSQL吧,对此感到有些无奈。
以下是搜索到的一篇相关文章内容。
PHP配置步骤:
在php.ini文件中设置如下内容,找到
;extension=php_mssql.dll 将前面的分号移除
找到extension_dir = d:\extension\
你的php.ini里面可能不是d:\extension\
改为指向php安装目录下的extensions目录中的php_mssql.dll路径,若未移动该文件(假设php安装路径为d:\php)
则修改为extension_dir=d:\php\extensions\
随后重新启动Web服务器
这一步骤虽简单,但即使完成上述设置仍无法连接,错误信息如下:
MS SQL Server 数据库连接错误!请检查数据库主机变量设置是否正确!!!
主机变量设置已反复检查无误,翻阅网页后找到以下线索:
php.com资料:
I am trying to connect to SQL Server 2000 from PHP
I bumped to following warning:
Warning: mssql_connect(): Unable to connect to server: SERVER\Portal
....... on line 5
on line 5 there is:
$db_connect = mssql_connect('SERVER\Portal', 'sa', 'my_passwd');
I did the following
1.enabled php_mssql.dll extension in PHP.ini
2.every dll is in proper place(System32 or PHP folder),including ntwdblib.dll
I search lots of profile throught web ,but no one give me proper answer to resolve it.
after a few hour ,I found the problem was caused by
ntwdblib.dll ,which version is 7.00.839 ,when I replaced old ntwdblib.dll with the new
ntwdblib.dll ,which version is 8.00.194 ,all problem are solved.
We had some, read A LOT, of problems with MSSQL under Windows 2003.
We had 2 the same windows, php, php-ini, everything machines but only one could connect.
Unable to connect was the error message.
Finnaly we checked the version of ntwdblib.dll and the one distributed with PHP was 7.00....
and the version of the one on the SQL Server install was 8.00.... so we copied this one in
the php and apache dir and it worked.
问题就这样被找到了,惹祸的是它 ntwdblib.dll
ntwdblib.dll的主要作用是提供sql server连接服务。
我用的php版本是4.3.9,在安装它的服器的 windows/system32/ 下我查到ntwdblib.dll文件的版本是2000.2.8.0 ,这个版本支持的是sql server 7.0, 因为安装PHP时会把dlls下面的所有文件覆盖到系统
目录下,所以当我用它去连接 sql server 2000 的时候当然会是无法连接了。
后来我在一台正常安装sql server 2000 的服务器上查到 ntwdblib.dll的版本是 2000.80.2039.0,我把这个文件拷过去,覆盖掉以前的版本,重启服务器后,一切正常。
补充:如果数据库名的开头是数字时也会提示无法打开,这时要做的很简单,把数据库的名字用中括号 [ ]
括起来就搞定了,如 123bbs 改写成 [123bbs]就没有问题了,另外如果你的数据库名字与sql server中的保留字冲突的话也会出现这种情况,用中括号的方法一样可以解决。
最终,PHP无法正确连接sql server 2000的问题终于解决了,虽然耗费大半天的时间,但收获还是很大的,现在把它贴出来,也让遇到同样问题的兄弟们少走一些弯路。