Connecting your PHP application to MSSQL using FreeTDS

The following guide serves to assist with connecting (or re-connecting) your PHP web application running on a LAMP server with an MSSQL database.

The following has been tested on Ubuntu 14.04.3 LTS with MSSQL 2008 but should work with most flavours. It is assumed that you have a ‘standard’ LAMP installation performed with ‘tasksel’.

First we need to install the FreeTDS packages and restart Apache:

sudo apt-get install freetds-common freetds-bin unixodbc php5-sybase
sudo service apache2 restart

Once FreeTDS is installed we need to add the details of our MSSQL database to the FreeTDS configuration file /etc/freetds/freetds.conf. This can be achieved via the terminal using nano.

Your freetds.conf file should look something like this:

#! [A logical name for your server]
#  host = [IP or Hostname of your server]
#  port = [The listening port of your server (usually 1433)]
#  tds version = [8.0]

   MYSERVER
   host = 192.168.1.30
   port = 1433
   tds version = [8.0]

Note that if you need to use a specific instance you can add the following line to your configuration

instance = xxx (instance name, e.g. INST2)

To select the most appropriate tds version, consult the manual here.

You can now test your configuration in PHP…

?php
	$link = mssql_connect('MYSERVER', 'DB_USERNAME', 'DB_PASSWORD');
	if(!$link) {
		echo'Could not connect';
		die('Could not connect: ' . mssql_error());
	}
	echo'Database connected OK';
	mssql_close($link);
?

Be the first to comment on "Connecting your PHP application to MSSQL using FreeTDS"

Leave a comment

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.