Making a PHP Site on Linux Work with a Microsoft SQL Server Database
February 14th, 2003 by David Perrin in
A recent project at my current employer called for creating a new web frontend to an existing MSSQL database. My boss, having created a sophisticated MySQL and PHP-driven black diamond web site in PHP was enthused about the prospects of further web development with PHP. He suggested trying to get PHP on a Linux box to connect to a MSSQL database server.
An attempt at this task made months before ended in frustration. This time, after nibbling away at the task for a couple of days on a standard Red Hat system, success was had. Here's how.
Similar to Windows, one method of connecting to a MSSQL database is through an ODBC DSN (open database connection, data source name). The ODBC DSN specifies a MSSQL driver to make the connection to the database. Recent versions of Red Hat include the utility for creating the ODBC DSN, but not the driver.
The driver chosen and discussed in this article is a FreeTDS driver. TDS (tabular datastream) is a protocol used by Sybase and MSSQL. This driver enables the Linux machine to connect to the MSSQL server.
Once the driver is installed, you can configure an ODBC connection on your Linux machine to use the driver, which then allows a connection to MSSQL. Start by downloading and saving the FreeTDS driver.
[root@localhost]# lynx http://ibiblio.org/pub/Linux/ALPHA/freetds/freetds-0.60.tgz
Next, uncompress, configure and make the FreeTDS driver.
[root@localhost]# tar xvfz freetds-0.60.tgz [root@localhost]# cd freetds-0.60 [root@localhost]# ./configure --with-tdsver=7.0 --with-unixodbc
su to root if you are not already root.
[root@localhost]# make [root@localhost]# make install [root@localhost]# make clean
Now test the ability of FreeTDS to connect to your MSSQL server:
[root@localhost]# /usr/local/bin/tsql -S <mssql.servername.com> -U <ValidUser> Password: <password>
With luck, you'll see the following prompt
1>
Then, use Ctrl-C to exit.
If the tsql command doesn't return the 1> prompt, verify that you can get to your MSSQL server with
[root@localhost]# telnet <mssql.servername.com> 1433
If you're able to telnet to port 1433, try opening the Microsoft Query Analyzer. Use the login combination you tried above to verify that a user name and password combination exists for your SQL server.
Once you can get the 1> prompt from tsql, we can configure the TDS driver and make the ODBC connection.
[root@localhost]# cd /usr/local/etc
From /usr/local/etc/, edit freetds.conf. At the end of this file, add an entry something like this:
[TDS]
host = mssql.serverhost.com
port = 1433
tds version = 7.0
Red Hat comes with a graphic interface tool called ODBCConfig. We'll use it to set up our DSN.
From KDE, select K -> System -> ODBCConfig
From GNOME, select G -> Programs -> System -> ODBCConfig
Click on the Drivers Tab and click Add. The window should contain the following data:
Name: TDS Description: v0.60 with Protocol v7.0 Driver: /usr/local/lib/libtdsodbc.so Setup: /usr/lib/libtdsS.so FileUsage: 1
The rest can be blank. Click the check-mark in the upper left-hand corner. Select the TDS driver and click OK.
Name: MSSQLServer Description: TDS MSSQL (description isn't important) Servername: mssql.serverhost.com UID: sa PWD: Port: 1433
Then click the System DSN tab and select Add. Test out the unixODBC connection with:
[root@localhost]# isql -v MSSQLServer username password +---------------------------------------+ | Connected! | | | | sql-statement | | help [tablename] | | quit | | | +---------------------------------------+ SQL> use Northwind 0 rows affected SQL> SELECT TOP 1 CategoryName from Categories +-------------------------------+ | CategoryName | +-------------------------------+ | Beverages | +-------------------------------+ 1 rows affected SQL> quit
Now to test it using PHP, put this page in a web-viewable directory and try to view it from the browser.
--- begin odbctest.php---
<?
// connect to DSN MSSQL with a user and password
$connect = odbc_connect("MSSQLServer", "username", "password") or die
("couldn't connect");
odbc_exec($connect, "use Northwind");
$result = odbc_exec($connect, "SELECT CompanyName, ContactName " .
"FROM Suppliers");
while(odbc_fetch_row($result)){
print(odbc_result($result, "CompanyName") .
' ' . odbc_result($result, "ContactName") . "<br>\n");
}
odbc_free_result($result);
odbc_close($connect);
?>
--- end odbctest.php --
Should a SQL statement contain an error, PHP will return a cryptic, incomprehensible warning message via the driver. In debugging, it has been helpful to echo out the offending queries.
The web application that instigated this setup is now in its third month of production and is performing quite well.
Special Magazine Offer -- Free Gift with Subscription
Receive a free digital copy of Linux Journal's System Administration Special Edition as well as instant online access to current and past issues. CLICK HERE for offer
Linux Journal: delivering readers the advice and inspiration they need to get the most out of their Linux systems since 1994.
Subscribe now!
The Latest
Newsletter
Tech Tip Videos
- Nov-04-09
- Oct-29-09
- Oct-26-09
Recently Popular
From the Magazine
December 2009, #188
If last month's Infrastrucuture issue was too "big" for you then try on this month's Embedded issue. Find out how to use Player for programming mobile robots, build a humidity controller for your root cellar, find out how to reduce the boot time of your embedded system, and if you're new to embedded systems find out the basics that go into one. You can also read about the Beagle Board, the Mesh Potato and a spate of other interestingly named items. And along with our regular columns don't miss our new monthly column: Economy Size Geek.
Delicious
Digg
StumbleUpon
Reddit
Facebook








VOB to MOV Mac:Fantastic mac video converter!
On October 28th, 2009 shirleyyang says:
VOB to MOV Mac offers you the best way to convert VOB to MOV for Mac. Only a few clicks within a few seconds, you will get what you want with high qulaity. Powerful VOB to MOV Mac can convert VOB to all the other popular formats on Mac including AVI, MPEG, WMV, etc as well.
__________________________VOB to MOV Mac
DPG Converter is a superior
On April 21st, 2009 asdas (not verified) says:
DPG Converter is a superior video converter specially for Nintendo DS users, which helps convert video to DPG video. DPG Converter can decode nearly all video and audio formats and convert them to DPG/DPG2/DPG3/DPG4 video or MP3/MP2 audio. With DPG Converter, you can easily enjoy all kinds of videos/audios on Nintendo DS.
UniverSQL,a point-and-click
On November 18th, 2008 Anonymous -8 (not verified) says:
UniverSQL,a point-and-click setup, remote admin tools (for both Windows and Linux) and very high performance led my company to choose this approach.
_______________________________________
video converter for mac…..
freeTDS on Edgy EFT
On March 18th, 2007 GrahamD (not verified) says:
Great article, but I'm stuck on the last step.
First a few tips for Ubuntu users, you need unixodbc-dev and tdsodbc. With these packages I could compile freeTDS. Connected to my database with isql and could query the tables.
When I tried the example using php I get the error "Call to undefined function odbc_connect()"
Any ideas ?
Graham
I don't think odbc support
On April 17th, 2008 Greg1976 (not verified) says:
I don't think odbc support is installed with PHP under Ubuntu.
Try
apt-get install php4-odbc
OR
apt-get install php5-odbc
Help please!!
On October 20th, 2005 Reda (not verified) says:
Hi everybody, how are you?
I'm really lost, i've been trying to make this work several weeks but i can't...!! did anyone make it?
my website is hosted on a linux server (redhat 7.2) and i would like to connect the mysql database to a mssql database on a windows server!!
i downloaded several versions of freetds (0.60, 0.62...) but the terminal returns some errors when i run 'make', here is part of the errors:
../../include/tdsodbc.h:26:17: sql.h: No such file or directory
../../include/tdsodbc.h:27:20: sqlext.h: No such file or directory
../../include/tdsodbc.h:28:22: odbcinst.h: No such file or directory
In file included from odbc.c:60:
odbc_util.h:28:17: sql.h: No such file or directory
odbc_util.h:29:20: sqlext.h: No such file or directory
In file included from odbc.c:63:
prepare_query.h:28:17: sql.h: No such file or directory
prepare_query.h:29:20: sqlext.h: No such file or directory
make[3]: *** [odbc.lo] Erreur 1
make[3]: Quitte le répertoire `/root/freetds-0.63/src/odbc'
make[2]: *** [all-recursive] Erreur 1
make[2]: Quitte le répertoire `/root/freetds-0.63/src/odbc'
make[1]: *** [all-recursive] Erreur 1
make[1]: Quitte le répertoire `/root/freetds-0.63/src'
make: *** [all-recursive] Erreur 1
is that normal ?
i also wanted to try : ./configure --with-mssql=/usr/local/freetds but should i put after '='? what path is '/usr/local/freetds'??
Thank you thank you so much for your help.
have a good day
about :Making a PHP Site on Linux Work with a Microsoft SQL
On August 6th, 2005 Anonymous says:
Hi,
All the processes have been successful before this step:
isql -v MyLServer username password
when I execute isql -v MyServer UsedId Password
i get the message
[unixODBC][FreeTDS][SQL Server]Unable to connect
to data source
[ISQL]ERROR: Could not SQLConnect
.
when i open the DataManager and expand the
ODBC > System Data Source > MyServer
input for ID
and PWD
After giving the input I get the message
[unixODBC][FreeTDS][SQL Server] unable to connect to the data source
and how could I can reconfigure the packages because in the Linux cd all the packages are rpms.
Plz , show me the way.............
[IM002][unixODBC][Driver Manager]Data source name not found, and
On August 13th, 2005 bill (not verified) says:
Please make sure that the named section that contains the ODBC driver for MySQL in your odbcinst.ini file matches the driver name you point to in your odbc.ini file.
For example...
[MySQL-test]
Description = MySQL database MusicDB
Driver = MySQL
Server = 192.168.0.17
Database = test
Port = 3306
Socket =
Option =
Stmt =
Since this file points to a driver named "MySQL" your obdcinst.ini file section for that driver needs to start with
[MySQL]
There is an OpenOffice howto on the net that overlooks this important detail.
Hope this helps.
Cheers,
Bill
[ISQL]ERROR: Could not SQLConnect
On October 9th, 2007 Anonymous (not verified) says:
Hi, I have the same problem:
-----------------------------------------------------------------------
[root@localhost ~]# isql -v MSSQLServer linuxuser mypassowrd
[S1000][unixODBC][FreeTDS][SQL Server]Unable to connect to data source
[ISQL]ERROR: Could not SQLConnect
-----------------------------------------------------------------------
I get the error: Could not SQLConnect; I alreadu made sure the odbcinst.ini & odbc.ini have the right settings!
any suggestions will be gladly apreciated!
thank you
[ISQL]ERROR: Could not SQLConnect
On February 20th, 2009 Anonymous (not verified) says:
Hi, I have the same problem:
-----------------------------------------------------------------------
[root@localhost ~]# isql -v MSSQLServer linuxuser mypassowrd
[S1000][unixODBC][FreeTDS][SQL Server]Unable to connect to data source
[ISQL]ERROR: Could not SQLConnect
-----------------------------------------------------------------------
I get the error: Could not SQLConnect; I alreadu made sure the odbcinst.ini & odbc.ini have the right settings!
If u hav got the answer please let me know.....
Making a PHP Site on Linux Work with a Microsoft SQL Server Data
On November 9th, 2004 Anonymous says:
your article has been really helpful
I am able to connect to the DSN from the terminal.
but i am not able to connect to the DSN from PHP
"Warning: SQL error: [unixODBC][Driver Manager]Data source name not found, and no default driver specified, SQL state IM002 in SQLConnect"
Pls HELP
Re: Making a PHP Site on Linux Work with a Microsoft SQL Server
On July 31st, 2003 Anonymous says:
For an excellent out of the box solution, I highly recommend looking into UniverSQL.
A point-and-click setup, remote admin tools (for both Windows and Linux) and very high performance led my company to choose this approach.
NB
Re: Making a PHP Site on Linux Work with a Microsoft SQL Server
On July 31st, 2003 Anonymous says:
For an excellent out of the box solution, I highly recommend looking into UniverSQL.
A point-and-click setup, remote admin tools (for both Windows and Linux) and very high performance led my company to choose this approach.
NB
Re: Making a PHP Site on Linux Work with a Microsoft SQL Server
On March 4th, 2003 Anonymous says:
Hi, how can i configure unixODBC without gui, I'm using
R.H. 8.0
unixODBC-2.2.5
freetds-0.61
i'm trying with template files, but it doesn't work, the freetds.log file looks like:
2003-03-04 12:40:22.003738 iconv will convert client-side data to the "" character set
2003-03-04 12:40:22.003928 IP address pointer is NULL
2003-03-04 12:40:22.003949 Server SYBASE not found!
Re: Making a PHP Site on Linux Work with a Microsoft SQL Server
On March 11th, 2003 Anonymous says:
The unixODBC gui writes to /etc/odbc.ini and /etc/odbcinst.ini
If you haven't already, try something like this in odbc.ini:
[MSSQLServer]
Description = TDS MSSQL
Driver = TDS
Servername = your.server.com
UID = sa
PWD =
Port = 1433
and
in odbcinst.ini...
[TDS]
Description = v0.6 with protocol v7.0
Driver = /usr/local/freetds/lib/libtdsodbc.so
Setup = /usr/lib/libtdsS.so
FileUsage = 1
CPTimeout =
CPReuse =
Re: Making a PHP Site on Linux Work with a Microsoft SQL Server
On February 21st, 2003 hpoyatos (not verified) says:
In the most recent versions of PHP (4.2.x, 4.3.x), exists another way to access a Microsoft SQL Server from PHP in Linux. Compile the PHP source in parameter :
$./configure --with-mssql=
Examples :
$./configure --with-mssql=/usr/local/freetds
$./configure --with-mssql=/usr/local/lib/
Then, $make, $make test, $make install...
If you will set the correct directory, you won't have problems.
Make a page with and search the mssql table. If have one, The direct suport to MSSQL is done.
Now, I can use the mssql commands (mssql_connect(), mssql_bind()) to work. More informations in http://www.php.net/manual/en/ref.mssql.php.
Sorry for my terrible English ! Hope it helps.
Please Help!!
On October 20th, 2005 Reda (not verified) says:
Hi everybody, how are you?
I'm really lost, i've been trying to make this work several weeks but i can't...!! did anyone make it?
my website is hosted on a linux server (redhat 7.2) and i would like to connect the mysql database to a mssql database on a windows server!!
i downloaded several versions of freetds (0.60, 0.62...) but the terminal returns some errors when i run 'make', here is part of the errors:
../../include/tdsodbc.h:26:17: sql.h: No such file or directory
../../include/tdsodbc.h:27:20: sqlext.h: No such file or directory
../../include/tdsodbc.h:28:22: odbcinst.h: No such file or directory
In file included from odbc.c:60:
odbc_util.h:28:17: sql.h: No such file or directory
odbc_util.h:29:20: sqlext.h: No such file or directory
In file included from odbc.c:63:
prepare_query.h:28:17: sql.h: No such file or directory
prepare_query.h:29:20: sqlext.h: No such file or directory
make[3]: *** [odbc.lo] Erreur 1
make[3]: Quitte le répertoire `/root/freetds-0.63/src/odbc'
make[2]: *** [all-recursive] Erreur 1
make[2]: Quitte le répertoire `/root/freetds-0.63/src/odbc'
make[1]: *** [all-recursive] Erreur 1
make[1]: Quitte le répertoire `/root/freetds-0.63/src'
make: *** [all-recursive] Erreur 1
is that normal ?
i also wanted to try : ./configure --with-mssql=/usr/local/freetds but should i put after '='? what path is '/usr/local/freetds'??
Thank you thank you so much for your help.
have a good day
Re: Making a PHP Site on Linux Work with a Microsoft SQL Server
On February 18th, 2003 Anonymous says:
Excellent!!!!
I've searched for weeks for a guide like this one.
It worked for me straith forward...
My system:
Red Hat 8.0
FreeTDS 0.6
Thanks.
Re: Making a PHP Site on Linux Work with a Microsoft SQL Server
On June 27th, 2005 Andika (not verified) says:
I'm using Mandrake with PHP, and i want to connect it to SQL Server...
I'm using Freetds 0.6, but still confuse...
and i couldn't find this file Driver =/usr/local/freetds/lib/libtdsodbc.so
[root@10 source]# isql -v MSSQLServer ccjkt password
isql: error while loading shared libraries: libreadline.so.5: cannot open shared object file: No such file or directory
[root@10 source]#
What should i do ???
Thank's
Andika Arsi P
Please Help!!
On April 27th, 2005 Reda (not verified) says:
Hi, i've been trying connecting my mysql databased hosted on a linux server (red hat) to an mssql database on windows but i couldn't do iy!! could you please tell me how you did?
thank you very much
Re: Making a PHP Site on Linux Work with a Microsoft SQL Server
On February 17th, 2003 Anonymous says:
Just for those bashing this article because Linux Journal posted an article about connecting to MS SQL Server via PHP and FreeTDS.
The article was written for real world use of Linux, such as, in large corporations.
In large corporations, they use a variety of databases: IBM DB2, Oracle, MS SQL, etc...
If the web servers in the company use PHP on Linux machines, how do you retrieve data from the MS SQL database when MS only supports accessing MS SQL from Windows? Answer: FreeTDS and unixODBC.
Both FreeTDS and unixODBC are open source software.
Moreover, this article was written for paying customers of their magazine - the ones most likely using Linux in the corporate world - ie. the real world.
Boycott egov-OS and stop the Microsfot madness!
On February 15th, 2003 Anonymous says:
Boycott Microsoft and the Egov-OS conference. NYFAIRUSE
is leading aprotest. Microsoft wants to destroy Free Software and your rights!
No more Microsoft articles in Free Software Journal!
They can pay for their own advertising!
Re: Boycott egov-OS and stop the Microsfot madness!
On February 16th, 2003 Anonymous says:
Get a grip! The facts are that computing involves both free and non-free software. There is no harm in being familiar with both Linux/Unix and Microsoft products.
Re: Boycott egov-OS and stop the Microsfot madness!
On February 17th, 2003 dmarti (not verified) says:
Companies don't shut down existing, working, systems if they don't have to. It's better for free software to integrate with proprietary software, and then replace it piece by piece when the user decides to.
How did the GNU Project get users, and get good? By making a good editor, tools, and libraries that ran on proprietary Unix. We have a stable all-free system today because people spent 1984-1991 developing and testing parts of GNU in combination with proprietary software.
Re: Boycott egov-OS and stop the Microsfot madness!
On February 19th, 2003 Anonymous says:
Don, although that it might be useful to sometimes integrate with existing systems, over all, this is a bad philosophy. The desktop environment is different from the server market, but the desktop market is more integrated and the verticle markets makes this approach not workable.
Even in the server market, this is a loosing proposition. For example, SAMBA has been intentionally broken on a number of occasion.
And then there is the issue of constantly playing follow the leader rather than spending the engery on being innovative.
Other all, there are a lot of hard working people working to replace the Microsoft nameless SQL Server with Free Software, and they deserve complete support on this issue.
Ruben
Re: Making a PHP Site on Linux Work with a Microsoft SQL Server
On February 14th, 2003 Anonymous says:
why use PHP's ODBC functions with FreeTDS?
http://www.php.net/mssql
Almost completely identical with PHP's MySQL functions, you can access the MS-SQL server directly without unixODBC. Simply compile PHP --with-mssql=/path/to/freetds and you're good to go.
Re: Making a PHP Site on Linux Work with a Microsoft SQL Server
On February 18th, 2003 Anonymous says:
But it only works if you are runing PHP on Windows platform! This article is talking about running PHP on a Linux platform.
Re: Making a PHP Site on Linux Work with a Microsoft SQL Server
On February 17th, 2003 Anonymous says:
Because you might want to write code that abstracts away the database connection, and doesn't tie you to one database server. And you might want to migrate to another db later, like sqlserver -> postgreSQL ;)
Re: Making a PHP Site on Linux Work with a Microsoft SQL Server
On February 17th, 2003 Anonymous says:
Enable PHP/MS SQL with --with-mssql, this is, by far, the best way to connect to MSSQL from PHP. Don't waste your time with ODBC. I use PHP via FreeTDS everyday without ODBC, using this setup.
Boycott of MS after the egov-os Fiacso
On February 15th, 2003 Anonymous says:
Boycott Microsoft and the Egov-OS conference. NYFAIRUSE is leading aprotest. Microsoft wants to destroy Free Software and your rights!
No more Microsoft articles in Free Software Journal!
They can pay for their own advertising!
Re: Making a PHP Site on Linux Work with a Microsoft SQL Server
On February 14th, 2003 Anonymous says:
Just a few questions:
1) How dog-slow is the ODBC connection?
2) Doesn't this violate your MS SQL Server license requiring you not to work with "viral" GPL software?
3) Why pay for MS SQL when there are many better alternatives from commercial companies that actually contribute to the community?
4) Why use a Detroit Diesel when you could use a Briggs & Stratton to do the job?
5) Don't you have to have a different server (Win NT or 2K) for MS SQL?
Properly annotated, this would be LAP, not LAMP or maybe WIMPO - (Windows/MS SQL/through PHP over ODBC).
I am certain some people might find this interesting, but Microsoft will eventually restrict you from doinng this with their licenses, if they haven't already.
Your article is well-written and good - don't get me wrong. It just seems more of a "why?" question to me.
Re: Making a PHP Site on Linux Work with a Microsoft SQL Server
On February 17th, 2003 Anonymous says:
To answer your first question, not at all. ODBC doesn't slow down your database connections, you won't see any noticeable performance penalty vs. native database connections (all other factors being equal). I've used unixodbc for over 3 yrs on linux/bsd, and seen benchmark testing done on it with very high loads, albeit not with PHP.
I have another question for you - if you're db is already SQLServer, why write your code for one database server, and then rewrite for another? With ODBC all you do is point your datasource at another driver, and rely on SQL compatibility between db's (which is very do-able for most web apps, among them those I've tried are mssql/postgreSQL/mysql/sybase/oracle/db2).
Re: Making a PHP Site on Linux Work with a Microsoft SQL Server
On February 17th, 2003 Anonymous says:
Why?
I was using php oracle/informix for web development for two years. As a result of the recent IT fallout, I found myself working for a company as an ASP/ASP.net and MSSQL programmer. Which was not good, but I produced some very usefull applications.
My company also supported numerous static sites on Linux. The powers that be decided that it would be best to move off of the linux server, because I could make "much better sites" on the Microsoft platform. I don't think they really understood the difference between PHP and ASP, but I had to use MSSQL for the database. Because "We had standardized on it" and, for Chrissakes, "security reasons".
By accessing MSSQL from PHP, not only are we still using Linux as a server, but I get to use good tools again to do my job.
if the EvilM stops allowing access through FreeTds, there are only two options:
1) Take two months to rewrite everything that has already been written at considerable cost.
2) Take two hours to install either MySQL or Postgress, which will result in an overall savings.
Like the other guy said, take what you can in small steps.
Re: Making a PHP Site on Linux Work with a Microsoft SQL Server
On February 17th, 2003 Anonymous says:
To answer the question of "why?": because MS SQL is out there, and people need to be able to interact with it -- just like they need to interact with Windows NT domains (Samba), with Windows closed-source programs (Wine), and with any number of other things that Microsoft has inflicted upon the world.
Because MySQL, for all its zippiness, does not compare favorably with MS SQL in terms of feature set; and while there are other databases available on Linux that do, sometimes Linux advocacy requires taking things one step at a time.
Post new comment