简体   繁体   English

使用PDO_DBLIB连接到MS SQL数据库的PHP错误

[英]PHP error connecting to MS SQL database using PDO_DBLIB

I am attempting to use PHP's PDO_DBLIB driver to connect to a remote database and am having some issues. 我试图使用PHP的PDO_DBLIB驱动程序连接到远程数据库,并遇到一些问题。

The database is connectable via the same environment using telnet and a SQL client. 数据库可以使用telnet和SQL客户端通过相同的环境进行连接。 However, connecting using the following code in PHP does not work: 但是,在PHP中使用以下代码进行连接不起作用:

<?php
$conn = new PDO('dblib:dbname=TestDB;host=RemoteServer;charset=utf8', 'my_user', 'my_pass');

Running this code, whether it be from the command line or Apache, yields the following error: 运行此代码,无论是来自命令行还是Apache,都会产生以下错误:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] Unable to connect: Adaptive Server is unavailable or does not exist (severity 9)' 致命错误:未捕获异常'PDOException',消息'SQLSTATE [HY000]无法连接:Adaptive Server不可用或不存在(严重级9)'

I am able to connect to the database using the same code on a different web server, which leads me to believe that it's a configuration issue. 我能够在不同的Web服务器上使用相同的代码连接到数据库,这让我相信这是一个配置问题。 The php.ini files on the two servers look relatively the same. 两台服务器上的php.ini文件看起来相对相同。 They each have the same PDO libraries enabled with the same options configured. 它们各自具有相同的PDO库,并配置了相同的选项。

Does anyone have any idea why this could be happening? 有谁知道为什么会发生这种情况?

Turns out that it was a much simpler issue than I thought. 事实证明这是一个比我想象的更简单的问题。 For whatever reason, the development server was not using Port 1433 as the default port in the connection and was instead using Port 4000. 无论出于何种原因,开发服务器没有使用端口1433作为连接中的默认端口,而是使用端口4000。

I discovered this by enabling the logs in the freetds.conf file and monitoring them as I was making the request. 我通过启用freetds.conf文件中的日志并在我发出请求时监视它们来发现这一点。

Also, something to note: The DBLIB extension uses a colon (:) as a separator between the host and the port instead of the comma. 另外,需要注意的事项:DBLIB扩展使用冒号(:)作为主机和端口之间的分隔符而不是逗号。 Unfortunately, the error that you receive when you use a comma isn't very descriptive, so hopefully someone benefits from this discovery. 不幸的是,您使用逗号时收到的错误不是很具描述性,所以希望有人从这个发现中受益。

Write port into freetds.conf directly for this host: 直接为此主机将端口写入freetds.conf

[RemoteServer]
    host = RemoteServer
    port = 1433

And leave php-code us is: 并留下PHP代码我们是:

$conn = new PDO('dblib:dbname=TestDB;host=RemoteServer;charset=utf8', 'my_user', 'my_pass');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM