PHP Access To An MSSQL Database From Debian with ODBC And FreeTDS

Note:  on some Ubuntu system you could incur on issues (Data source name not found, and no default driver specified)

First install the necessary packages:

# apt-get install tdsodbc unixodbc php5-odbc

ODBC Driver registration:

# nano /etc/freetds/tds.driver.template
[FreeTDS]
Description = ciao
Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
Seteup = /usr/lib/x86_64-inux-gnu/odbc/libtdsS.so

Now the edit the DSN file:

# nano /etc/freetds/tds.dsn.template

Replace the <...> with your settings.

[MSSQL]
Driver = FreeTDS
Description = <Description>
Server = <IP>
Port = 1433
Database = <DatabaseName>

Ok, now you need to get these templates inserted into the unixODBC system:

# odbcinst -i -d -f /etc/freetds/tds.driver.template
# odbcinst -i -s -f /etc/freetds/tds.dsn.template

check file permission of /etc/odbc.ini and /etc/odbcinit.ini

check php extension /etc/php5/mods-available/odbc.ini

; configuration for php ODBC module
; priority=20
extension=odbc.so

test connection
# isql -v MSSQL user pwd

Test PHP connection  to MS SQL server by example:

<?php

# connect to a DSN "DSN_NAME" with a user "Bob" and password "Marley"
$connect = odbc_connect("DSN_NAME", "Bob", "Marley");

# query the users table for all fields
$query = "SELECT * FROM users";

# perform the query
$result = odbc_exec($connect, $query);

# fetch the data from the database
while(odbc_fetch_row($result)) {
$field1 = odbc_result($result, 1);
$field2 = odbc_result($result, 2);
print("$field1 $field2\n");
}

# close the connection
odbc_close($connect);

?>