Connect to MS-SQL server from PHP-Linux

Having searched for quite a long while, here is how I figured out the way to connect to a Microsoft SQL server from Linux using PHP mssql extension module. (Thanks to Danne Lundqvist)

Step 1) Install FreeTDS

First download and install FreeTDS from freetds website. Use the following build commands to enable support for MS SQL Server (as root or using sudo).

./configure --enable-msdblib --prefix=/usr/local/freetds
make && make install

touch /usr/local/freetds/include/tds.h
touch /usr/local/freetds/lib/libtds.a

Step 2) Download the PHP source and recompile

It is advised to always use the source of the same PHP version you have installed!

cd php*/ext/mssql
./configure --with-mssql=/usr/local/freetds

At this point, ./modules/ must have been created.

Step 3) Install the mssql extension

cp modules/ /usr/lib/php5/20060613+lfs/

The extension is in the right place and all you have to do now is to make sure PHP actually loads it. To do this add the extension somewhere in the /etc/php5/apache2/php.ini file. For example in the section Dynamic Extensions to keep it somewhere logical.

Step 3) Restart the web server

If using the Apache 2 web server you would normally issue

/etc/init.d/apache2 restart

Step 4) Post installation

Edit freetds.conf file in /usr/local/freetds/etc/freetds.conf.

Sometimes it is difficult getting the connection work without adding it to the the freetds.conf. Especially since you may have to use different values for the tds version directive depending on the MS SQL Server version. Examples:

host =
port = 1433
tds version = 7.0

Here is a sample PHP script to test the connection:

    ini_set('display_errors', 1);

    $link = mssql_connect('logisticsServer','sa','pw');
    if (!$link) {
        die('Something went wrong while connecting to MSSQL');        

    $sql = "__SQL_QUERY__";

    $qry = mssql_query($sql);
    $res = mssql_fetch_array($qry);




You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *