Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

The database is connectable via the same environment using telnet and a SQL client. However, connecting using the following code in PHP does not work:

<?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:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] Unable to connect: Adaptive Server is unavailable or does not exist (severity 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. The php.ini files on the two servers look relatively the same. They each have the same PDO libraries enabled with the same options configured.

Does anyone have any idea why this could be happening?

like image 702
user543936 Avatar asked Aug 18 '11 02:08

user543936


2 Answers

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.

I discovered this by enabling the logs in the freetds.conf file and monitoring them as I was making the request.

Also, something to note: The DBLIB extension uses a colon (:) as a separator between the host and the port instead of the comma. Unfortunately, the error that you receive when you use a comma isn't very descriptive, so hopefully someone benefits from this discovery.

like image 154
user543936 Avatar answered Oct 31 '22 11:10

user543936


Write port into freetds.conf directly for this host:

[RemoteServer]
    host = RemoteServer
    port = 1433

And leave php-code us is:

$conn = new PDO('dblib:dbname=TestDB;host=RemoteServer;charset=utf8', 'my_user', 'my_pass');
like image 39
Serhii Topolnytskyi Avatar answered Oct 31 '22 13:10

Serhii Topolnytskyi