Connecting PHP to Microsoft SQL Server on Linux

Here is how to get PHP 5.2 on Linux (specifically Debian/Ubuntu) talking to a Microsoft SQL Server database:

1. Install FreeTDS and the PHP MS SQL extension
$ sudo apt-get install freetds-common freetds-bin unixodbc php5-sybase

Note: That is correct, the MS SQL extension is in the “php5-sybase” package.

2. Restart Apache
$ sudo /etc/init.d/apache2 restart

3. Test FreeTDS
$ tsql -H -p 1433 -U yourusername -P yourpassword -D yourdatabasename

If it connects, it’s working. Note: If you try to SELECT an NTEXT or NVARCHAR column you may get an error saying “Unicode data in a Unicode-only collation or ntext data cannot be sent to clients using DB-Library (such as ISQL) or ODBC version 3.7 or earlier”. That is expected and will be fixed in the next step.