siannone siannone - 3 months ago 83x
PHP Question

Cannot connect to MS SQL Server using PDO

The last 2 days I've spent a lot of time trying to figure out how to connect to MS SQL server hosted on Azure using PHP from an Ubuntu 14.04 server.

The code responsible to initiate the connection to the remote database is the following:

public function connect()
$this->databaseConnection = new \PDO(
catch (\PDOException $e)
throw new \Exception('Failed to connect to the database: '.$e->getMessage());

And every time I try to connect I receive:

Failed to connect to the database: SQLSTATE[01002] Adaptive Server connection failed (severity 9)

The problem is that this is a very general error and there's no way for me to understand what's causing the issue.

This is my /etc/freetds.conf configuration:

host =
port = 1433
tds version = 7.2
client charset = UTF-8

And this is the
tsql -C

Compile-time settings (established with the "configure" script)
Version: freetds v0.91
freetds.conf directory: /etc/freetds
MS db-lib source compatibility: no
Sybase binary compatibility: yes
Thread safety: yes
iconv library: yes
TDS version: 4.2
iODBC: no
unixodbc: yes
SSPI "trusted" logins: no
Kerberos: yes

In addition to this, I tried making some test using
functions and even if I was able to successfully connect to the database most of the queries didn't work.


The problem was caused by 2 different issues.

The first one was related to a wrong FreeTDS configuration. The freetds.con global section needs to be like this:

    tds version = 8.0

The second one was caused by the fact that the username must be specified in the following way when connecting to a MSSQL server hosted on Azure:


Where the specific server configuration in freetds.conf looks something like this:

    database = <databaseName>
    host = <serverName>
    port = 1433
    tds version = 8.0

So the PHP DB connection will look like something like this:

$this->databaseConnection = new \PDO(