Do you need to connect to a MSSQL database from a Linux, Apache, PHP enviroment? Are you tired of going through endless documentation? Could the production of goat cheese be more profitable than being a freelance web developer?
While I still have no idea about the third, there’s an easy solution for the first two problems!
Before you continue, please be warned I am sharing because it worked for me and I think it’s useful, not because I know everything about it. This article is an expansion to Daniel Lang’s PHP 5.3.6 + MSSQL + FreeTDS article.
Basically, all you need to do is to compile FreeTDS and the MSSQL PHP extension. On a debian-flavoured system (Linux Mint 13 here), this is how you do it.
Fetch the FreeTDS package and compile the library.
sudo su cd ~ mkdir sources wget ftp://ftp.astron.com/pub/freetds/stable/freetds-stable.tgz tar -x freetds-stable.tgz cd freetds-0.91 ./configure --enable-msdblib --prefix=/usr/local/freetds make && make install cp include/tds.h /usr/local/freetds/include cp src/tds/.libs/libtds.a /usr/local/freetds/lib
Now we need to compile the MSSQL PHP extension. For that you need to fetch the source of your PHP version. You can get it with:
My version is 5.3.10 so let’s use that for the example.
cd .. # go back to "sources" wget https://github.com/php/php-src/archive/php-5.3.10.zip # note the version unzip php-5.3.10.zip cd php-src-php-5.3.10/ext/mssql phpize ./configure -–with-mssql=/usr/local/freetds make
Let’s copy the extension to the PHP extensions dir. To check where on your system that is:
php -i | grep extension_dir
Mine is at /usr/lib/php5/20090626/, so…
cp modules/mssql.so /usr/lib/php5/20090626/
Proceed to edit your php.ini file (mine is at /etc/php5/apache/php.ini) and add this directive
Please note that if you are running your PHP scripts (with MSSQL code) through the CLI (like usually with cron jobs), you will also need to edit /etc/php5/cli/php.ini in the same fashion.
Now, for each server you need access to, you will need to add a corresponding entry into the freetds.conf config file. This is located in /usr/local/freetds/. Refer to this FreeTDS page for all available options.
Considering this, I added the following:
[testserver] host = 126.96.36.199 port = 1433 tds version = 7.0 instance = Instance_name
You can check if you configured your server correctly with the troubleshooting/query tool that comes with FreeTDS:
ln /usr/local/freetds/bin/tsql /usr/bin # make the tsql tool available anywhere tsql -S testserver -U some_user
If all is well, the server will ask you for your password. You can then type any query and try it out. Note that the query is executed by the word GO (must be in it’s own line).
1> SELECT * FROM INFORMATION_SCHEMA.TABLES 2> GO
At this point there’s nothing more than to restart your apache server (service apache2 restart) and you are good to go!
mssql_connect('testserver', 'some_user', 'some_pass');
If you have a better solution please let me know.