Connecting to MSSQL databases with PHP from Linux

I needed to get some data from existing MSSQL databases with PHP. Connecting to such servers is a bit more tricky than mysql, because the mssql extension from php needs also a correctly configured TDS installation. But we’re lucky, there is an opensource implementation of the tds protocoll called FreeTDS. If you don’t want to use tds you can also try to get it to work with ODBC, but ODBC is very slow and that’s why it’s also not part of this blog post.

So here we go…

1. Installation of FreeTDS:
– Get the latest release of FreeTDS from here: http://freetds.org/ (the time i write this it’s 0.82)
– Extract and compile it:

tar xzvf freetds-stable.tgz
cd freetds-0.82/
./configure --prefix=/opt/freetds --with-tdsver=8.0
make install

– Edit /opt/freetds/etc/freetds.conf and add your MSSQL server like this:

host = hostname or ip
port = 1433
tds version = 8.0

MSSQLserver is used in your php code afterwards, so it might be a good idea to think of an appropriate name.

2. Installation of PHP
– Get the latest release of PHP from here: http://www.php.net/downloads.php
– Extract and compile it:

tar xjvf php-5.3.0.tar.bz2
cd php-5.3.0/
./configure --prefix=/opt/php --with-apxs2 --with-mssql=/opt/freetds
make install

This is a very limited version of PHP just to show the required options in order to get PHP to work with MSSQL. If you have additional requirements like mysql-support or gd processing stuff you need to add those options to the configure call.

After that you need to tell Apache to load the appropriate module (libphp5.so). Add the following line to your httpd.conf file:

LoadModule php5_module /usr/lib/httpd/modules/libphp5.so

The location of the module may vary.

If everything went fine, you can now start to ‚CRUD‘ your MSSQL data. Have fun…