FreeTDS on Ubuntu with PHP

FreeTDS on Ubuntu with PHP

Connecting to MSSql form a linux environment is a very common thing now a days especially in the business/work environment. But run into more and more situations where I need this. Setting this up was a pain every time, and you would think this would just be a couple of easy command. Until you actually document the steps.

If only needed to install this on Ubuntu and with php7 so that is what im will be using in this tutorial.

First of all do and update, I always do a full update.

sudo apt-get update -y; sudo apt-get upgrade -y; sudo apt-get autoremove -y;

Then we are going to install all the necessary modules.

sudo apt-get install unixodbc unixodbc-dev freetds-dev tdsodbc freetds-bin php7.0-sybase

Once this is complete we will need to edit the freetds.conf file

sudo nano /etc/freetds/freetds.conf

You will need to add your server config to freetds, this can be added to the end of the file.

[ServerFriendlyName]
        host = ip_address or server_name
        port = 1433
        tds version = 8.0
        client charset = UTF-8

We can then test the connection

tsql -S ServerFriendlyName -U username -P password

Once you run this file you should get an output as follows:

locale is "en_US.UTF-8"
locale charset is "UTF-8"
using default charset "UTF-8"

Next we need to setup the connecting driver

sudo nano /etc/odbcinst.ini

If this file does not exist create it.

[FreeTDS]
Description = FreeTDS Driver
Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
Setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so
FileUsage = 1
CPTimeout = 5
CPReuse = 5

Make sure that your paths to the libtdsodbc.so & libtdsS.so are correct for your system

Next we need to add the data source

sudo nano /etc/odbc.ini

Again create the file it it does not exist.

[ServerFriendlyName]
Driver = FreeTDS
Servername = ServerFriendlyName
Port = 1433
Database = database

Now you should be all up and running and be able to test the connection again

isql -v ServerFriendlyName USERNAME PASSWORD

This should give you and output as follows:

OUTPUT
+---------------------------------------+
| Connected!                            |
|                                       |
| sql-statement                         |
| help [tablename]                      |
| quit                                  |
|                                       |
+---------------------------------------+
SQL

Here you can actually run sql command to your database etc.

Hope this helped someone.