LXXV. Microsoft SQL Server Functions


These functions allow you to access MS SQL Server database.


Requirements for Win32 platforms.

The extension requires the MS SQL Client Tools to be installed on the system where PHP is installed. The Client Tools can be installed from the MS SQL Server CD or by copying ntwdblib.dll from \winnt\system32 on the server to \winnt\system32 on the PHP box. Copying ntwdblib.dll will only provide access. Configuration of the client will require installation of all the tools.

Requirements for Unix/Linux platforms.

To use the MSSQL extension on Unix/Linux, you first need to build and install the FreeTDS library. Source code and installation instructions are available at the FreeTDS home page: http://www.freetds.org/

注: In Windows, the DBLIB from Microsoft is used. Functions that return a column name are based on the dbcolname() function in DBLIB. DBLIB was developed for SQL Server 6.x where the max identifier length is 30. For this reason, the maximum column length is 30 characters. On platforms where FreeTDS is used (Linux), this is not a problem.


The MSSQL extension is enabled by adding extension=php_mssql.dll to php.ini.

To get these functions to work, you have to compile PHP with --with-mssql[=DIR], where DIR is the FreeTDS install prefix. And FreeTDS should be compiled using --enable-msdblib.


这些函数的行为受 php.ini 的影响。

表格 1. MS SQL Server configuration options

mssql.timeout"60"PHP_INI_ALLAvailable since PHP 4.1.0.
mssql.batchsize"0"PHP_INI_ALLAvailable since PHP 4.0.4.
mssql.datetimeconvert"1"PHP_INI_ALLAvailable since PHP 4.2.0.
mssql.secure_connection"0"PHP_INI_SYSTEMAvailable since PHP 4.3.0.
mssql.max_procs"25"PHP_INI_ALLAvailable since PHP 4.3.0.
有关 PHP_INI_* 常量进一步的细节与定义参见附录 G


以下常量由本扩展模块定义,因此只有在本扩展模块被编译到 PHP 中,或者在运行时被动态加载后才有效。

MSSQL_ASSOC (integer)

MSSQL_NUM (integer)

MSSQL_BOTH (integer)

SQLTEXT (integer)

SQLVARCHAR (integer)

SQLCHAR (integer)

SQLINT1 (integer)

SQLINT2 (integer)

SQLINT4 (integer)

SQLBIT (integer)

SQLFLT8 (integer)

mssql_bind --  Adds a parameter to a stored procedure or a remote stored procedure
mssql_close -- Close MS SQL Server connection
mssql_connect -- Open MS SQL server connection
mssql_data_seek -- Moves internal row pointer
mssql_execute --  Executes a stored procedure on a MS SQL server database
mssql_fetch_array --  Fetch a result row as an associative array, a numeric array, or both
mssql_fetch_assoc --  Returns an associative array of the current row in the result set specified by result_id
mssql_fetch_batch --  Returns the next batch of records
mssql_fetch_field -- Get field information
mssql_fetch_object -- Fetch row as object
mssql_fetch_row -- Get row as enumerated array
mssql_field_length -- Get the length of a field
mssql_field_name -- Get the name of a field
mssql_field_seek -- Seeks to the specified field offset
mssql_field_type -- Gets the type of a field
mssql_free_result -- Free result memory
mssql_free_statement -- Free statement memory
mssql_get_last_message --  Returns the last message from the server
mssql_guid_string --  Converts a 16 byte binary GUID to a string
mssql_init --  Initializes a stored procedure or a remote stored procedure
mssql_min_error_severity -- Sets the lower error severity
mssql_min_message_severity -- Sets the lower message severity
mssql_next_result -- Move the internal result pointer to the next result
mssql_num_fields -- Gets the number of fields in result
mssql_num_rows -- Gets the number of rows in result
mssql_pconnect -- Open persistent MS SQL connection
mssql_query -- Send MS SQL query
mssql_result -- Get result data
mssql_rows_affected --  Returns the number of records affected by the query
mssql_select_db -- Select MS SQL database

add a note add a note User Contributed Notes
anders jenbo(located)pc denmark
04-Nov-2006 04:32
The 3 major headaicks I had while setting up MS SQL 2005, php 5.1.6 (apache 2.2 server) on Vista RC1 and getting them to comunicate.

TCP/IP and "Named Pipes Protocol" had to be enabled in the MS SQL Server. You do this in the Surface Area Configuration tool.

MS SQL 2005 should be set to mix mode login. Unless you use NT authentication in php.ini.
You can do this in duing install if you select advanced options.
If it's already installed you will have to use the SQL management Studio (properties->securety).

At first the php_mssql.dll didn't load properly (wan't showing up under phpinfo()) and gave no error message at startup, the cause of this was the ntwdblib.dll that came with php (273KB) replacing it with the one that came with MS SQL 2005 (269KB) fixed the issuse, incase you haven't installed MS SQL on your machine you can also find it on the net.
php at scrunch dot net
20-Sep-2006 12:36
With WinXP client, connecting to SQL Server 2005, via PHP on the command line (CLI).

If the serverr was installed with support for multiple instances, you can not connect to it, even when attempting to connect to the default instance.

Replace the ntwdblib.dll (7.00.839) provided by PHP with the one from SQL Server 2000 (8.00.194).

Otherwise you will see this message, which is not very helpful:
Warning: mssql_connect(): Unable to connect to server: ...
jorrit at ncode dot nl
21-Jul-2006 09:14
To connect to SQL Server 2005 you can download ntwdblib.dll from http://www.webzila.com/?wz=dll. Pick the smallest file there, the other one is French.
antoinehurkmans at hotmail dot com
11-Jul-2006 08:40
"if you are looking for the equivalent of  mysql_list_tables for mssql, try this..."

Please use the INFORMATION_SCHEMA views for this. Using the system tables for anything other than the occasional ad-hoc query is not recommended. See MSDN for more details.
23-May-2006 12:46
Another helpful hint in regards to SQL Server 2005 Express:

Make sure your SQL Server is set to  "SQL Server and Windows Authentication mode". By default it is NOT.

1) Open "SQL Server Management Studio Express"
2) Right-click server ("machinename\sqlexpress") and select "Properties".
3) Select "Security"
4) Select "SQL Server and Windows Authentication mode"
5) Restart SQL Server.
phil at hilands dot c-spam-om
20-May-2006 05:13

using freebsd and freetds I ran into the dates month being rolled back
01 jan would be 00
12 dec would be 11 nov

default setting is to 1 or true on the servers config
and the date issue I ran into was resolved

I don't know how the mssql.datetimeconvert setting works but if you're getting a roll back in dates might be worth making sure its on.

using ini_get when dealing with scripts that like to modify ini settings will save a headache if you use phpinfo() like me

*side note with the same settings in freetds php apache etc on a debian load I didn't have this issue even with mssql.datetimeconvert off
thnkloud9 at aol dot com
02-Mar-2006 05:54
I had major latency problems with DB connections using php_mssql.dll without the client tools.  I found that by default it was using TCP/IP as the default connection method.  Installing the SQL Server client tools and using the Client Network Utility to change my settings to use named pipes resolved this issue.  You can use the Client Utility to set up a named pipes server alias and reference that in your connect string.
jimmy dot cartrette at gmail dot com
22-Feb-2006 11:56
"Note: DBLib is obsolete and only supports SQL Server 4.x, 6.5, 7.0 and 8.x. "

Well, ntwdblib.dll is not distributed with SQL Native Client 2005 versions anymore, but it is what you need to use the mssql family functions with php. The distributed 7.x version with php does not work, but if you download the 8.x version distributed with SQL 2000 versions and replace it in your php directory, you can suddenly use mssql functions with no problems.
support at realone dot com
09-Dec-2005 12:04
Actually, it's xtype, not type. So the the correct query would be something like:

SELECT name FROM sysobjects WHERE xtype = 'u' [ORDER BY whatever]
info at pkcom do t co dot uk
01-Nov-2005 07:47
if you are looking for the equivalent of  mysql_list_tables for mssql, try this:

######## Listing table names
$query=mssql_query ( "select * from SYSOBJECTS where TYPE='U' order by NAME" , [connection resource]);
while ($row=mssql_fetch_row ( $query )){
   echo "$row[0]<br>";
erwin_nospam_moller at xs4all dot nl
06-Oct-2005 07:43
php5isapi / w2000 / ISS5

If you use the above configuration (isapi) and follow the suggestion to deselect 'cache isapi application' to avoid 100% processor usage, you might end up with an oocasional error:

The remote procedure call failed and did not execute.

It happened to me every third visit to the same page.
RE-enabling caching resolved the issue.

M$ has an article about this in their knowledgebase, stating that this option should always be selected and is only there for developmentpurposes. (undocumented feature. :P)

Deselecting this option forces IIS to reload ALL relevant dll's every time a request is received in memory, also VB/ASP.
Erick Robertson
20-Aug-2005 09:58
Some helpful functions.  Pretty simple, but very useful.

function mssql_begin_transaction() {
  mssql_query("BEGIN TRANSACTION");

function mssql_commit() {

function mssql_rollback() {

function mssql_insert_id() {
  $id = "";

  $rs = mssql_query("SELECT @@identity AS id");
  if ($row = mssql_fetch_row($rs)) {
   $id = trim($row[0]);

  return $id;
vangoethem at hotmail.com
10-Aug-2005 08:47
I had problems related to VARCHAR limitation to 255 characters (INSERT/UPDATE works, SELECT was truncated) using freetds driver (Linux platform).

By upgrading the TDS protocol to 8.0 (see freetds config file), I fixed the problem.
hbzxc at 126 dot com
27-Jun-2005 05:14
I am trying to connect to SQL Server 2000 from PHP
I bumped to following warning:
Warning: mssql_connect(): Unable to connect to server: SERVER\Portal
....... on line 5

on line 5 there is:
$db_connect = mssql_connect('SERVER\Portal', 'sa', 'my_passwd');

I did the following
1.enabled php_mssql.dll extension in PHP.ini
2.every dll is in proper place(System32 or PHP folder),including ntwdblib.dll

I search lots of profile throught web ,but no one give me proper answer to resolve it.

after a few hour ,I found the problem was caused by
ntwdblib.dll ,which version is 7.00.839 ,when I replaced old ntwdblib.dll with the new ntwdblib.dll ,which version is 8.00.194 ,all problem are solved.
13-May-2005 04:32
We had some, read A LOT, of problems with MSSQL under Windows 2003.
We had 2 the same windows, php, php-ini, everything machines but only one could connect. Unable to connect was the error message.

Finnaly we checked the version of ntwdblib.dll and the one distributed with PHP was 7.00.... and the version of the one on the SQL Server install was 8.00.... so we copied this one in the php and apache dir and it worked.
diegobandeira at ibest dot com dot br
08-Apr-2005 11:42

This code appears work fine and fast to me, like mysql or msaccess.
The server is working for an Intranet home page.

= new COM("ADODB.Connection");
$dsn = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=tsos;Data Source=(local);Application Name=SellCar";
$rs = $db->Execute("SELECT * FROM states order by name asc");

  while (!

Diego Bandeira.
boonkit at gmail dot com
29-Mar-2005 05:29
If you are having problems with freeTDS when trying to get access to unicode data from mssql, set 'tds version =7.0' at etc/freetds.conf
23-Mar-2005 11:51
With PHP 5 on a Windows 2000/IIS platform:

I have integrated authentication enabled in IIS.  I kept getting CGI timeouts on PHP pages for everyone but local administrators of the box.  The event log showed that PHP could not load php_mssql.dll, php_oci8.dll, and php_oracle.dll - 'Access Denied.' 

These extensions were executable by everyone, but the DLLs they depend on were not.  Had to add exec permissions for everyone to c:\winnt\system32\ntwdblib.dll as well as the oracle bin directory.
marcel at fluidleb dot com
31-Jan-2005 02:24
I've spent the last three days wild guessing why I could not connect to MS SQLServer 2000 and so I hope this might help someone else. Microsoft has purposefully closed the 1433 tcp port and others (maybe only to external ips) of the server. You can easily check if this is the case by looking at the Event Monitor. You should see an error produced by MSSQL SERVER/MSDE that basically says what I said. It suggests downloading and installing a security patch to open up the ports (but doesn't even say which update - remember this is Microsoft).

Do download Service Pack 3a (SP3a). It does indeed fix the problem.
Salman Majid
26-Jan-2005 01:36
Sorry, previous message was incomplete. I used odbc functions to connect to Ms-SQL server. I was on a work station and server was not accessible for unknow reasons. mssql functions did not work there so I had to use odbc.
Salman Majid
26-Jan-2005 01:15
I was having problem in connecting Ms-SQL server with mssql_connect(srvr,uid,pwd). I simply created a DSN to my Database and replaced it with "server_name". i.e.


it worked well
craig at _NO_SPAM_deconstructor dot net
14-Jan-2005 04:22
Just a quick note pertaining marcos1979ar (10/06/04) definitive installation of FreeTDS above.

When you run the following to test the installation:
/usr/local/freetds/bin/tsql -S <ip of the server> -U <User SQL>

And it results in the following error:
locale is "C"
locale charset is "ANSI_X3.4-1968"
src/tds/login.c: tds_connect: xx.xx.x.xx:1443: Connection refused
Msg 20009, Level 9, State 0, Server OpenClient, Line 0
Server is unavailable or does not exist.
There was a problem connecting to the server

All I found that needed to be changed was for the configure --prefix from:

./configure --prefix=/usr/local/freetds
./configure --prefix=/usr/local

Small but worth noting.
hbinduni at hslprpol dot com
20-Dec-2004 04:15
i found http://odbtp.sourceforge.net working fast, easy to use and to configure, and yes, it's multiplatform.
marc at NOSPAM dot durdin dot net
19-Nov-2004 12:19
Buried away in the mssql_field_length documentation is an important limitation that it is certainly worth knowing about *BEFORE* you do any database design:

Note to Win32 Users: Due to a limitation in the underlying API used by PHP (MS DbLib C API), the length of VARCHAR fields is limited to 255. If you need to store more data, use a TEXT field instead.

SQL Server natively supports VARCHAR up to 8000 characters.  Note that TEXT fields have substantially poorer performance (and are much more limited) than VARCHAR so you may want to design your databases accordingly...

You can also work around this limitation with the following:

   -- for example, with MyVarCharField VARCHAR(1000)
28-Oct-2004 08:55
This note is for mssql under a Windows environment.

If you are having problems connecting to MS SQL using the mssql PHP extension then I would suggest that you get a copy of the latest NTWDBLIB.DLL. Copy it to the directory where PHP expects to find it's dll files.

I had an issuse whereby I was unable to connect to a MS SQL Cluster and this resolved my problem.
Dimitri Tarassenko (mitka at mitka.us)
25-Oct-2004 03:37
To enable MS SQL functions in PHP on Fedora Core or RHEL3 without recompiling PHP and replacing the distribution PHP packages, download and install php-mssql and freetds RPMS from

effeese at gmail dot com
15-Oct-2004 09:28
in relation to the "unicode problem" mentioned by andrej at dairyweb dot com dot au I suggest use andrew at power-grid dot com's solution:

if you get a "Unicode data in Unicode-only collation or ntext data cannot be sent to clients using DB-Library (such as ISQL) or ODBC version 3.7 or earlier" error you can use this kind of code (in an MS environment, of course):
= new COM("ADODB.Connection");
$rs = $db->Execute("SELECT * FROM table");

while (!

hope it helps.
mworku at yahoo dot com
03-Oct-2004 12:49
If you want to utilize the freetds.conf file db parameters within
mssql_connect() function


       mssql_connect('MSSQL_8.0' , 'user' , 'pwd');

FreeTDS conf file

   host =
   port = 1433
   tds version = 8.0
08-Aug-2004 06:11
For phpBB if you are having a problem with user cannot connect to database I found that gentiboard's comments were the answer.

You have to change sql secure connection to on in php.ini
marcos1979ar at yahoo dot com dot ar
11-Jun-2004 06:07
Red Hat 9.0  Freetds 0.62.3  Apache 2.0.49  PHP 5.0.ORC3

Instucction, that premit connect a server Linux with a server Windows 2000 Server with SQL Server.

1-.  Download freetds -> www.freetds.org
2-.  tar -zxvf freetds-stable-tgz
3-.  cd freetds-0.62.3
4-.  ./configure --prefix=/usr/local/freetds --with-tdsver=8.0 --enable-msdblib --enable-dbmfix --with-gnu-ld

Note:  tdsver=8.0 if you use SQL 2000, tdsver=7.0 if you use SQL 7.0

5-.  make
6-.  make install
7-.  /usr/local/freetds/bin/tsql -S <ip of the server> -U <User SQL>

Note: For default User SQL is    sa    and the it have not password
For example: /usr/local/freetds/bin/tsql -S -U sa

8-.  Add the next text in freetds.conf ( /usr/local/freetds/etc )
host = <ip of the Server with Sql>
port = 1433
tds version = 8.0

Note: If you use SQL 2000 then tds version = 8.0
if you use SQL 7.0 then tds version = 7.0

9-.  Add the next text in the file /etc/ld.so.conf


1-.  Download apache  www.apache.org
2-.  tar -zxvf httpd-2.0.49.tar.gz
3-.  cd httpd-2.0.49
4-.  ./configure --prefix=/etc/httpd --enable-so
5-.  make
6-.  make install
7-.  Configure the file  -> httpd.conf ( /etc/httpd/conf/httpd.conf )
8-.  Probe the apache: /etc/httpd/bin/apachectl start
/etc/httpd/bin/apachectl stop


1-.  Download the PHP in this site (www.php.net)
2-.  tar -zxvf php-5.0-ORC3.tar.gz
3-.  cd php-5.0-ORC3
4-.  ./configure --with-apxs2=/etc/httpd/bin/apxs --enable-versioning --with-mssql=/usr/local/freetds --disable-libxml
5-.  make
6-.  make install
7-.  cp php.ini-DIST /usr/local/lib
8-.  Add the next line in /etc/httpd/conf/httpd.conf
AddType application/x-httpd-php .php


= mssql_connect ("<ip of the server SQL>", "sa", "");
mssql_select_db ("<Data Base>", $con);
$sql= "SELECT * FROM <Table>";
$rs= mssql_query ($sql, $con);
"The field number one is: ";
mssql_result ($rs, 0, 0);
mssql_close ($con);
Asad Moin
29-May-2004 10:48
I took the following steps to make PHP talk to SQL2000:

- Copy ntwdblib.dll file from your SQL server's  \winnt\system32 folder to the \winnt\system32 folder on the PHP box.

- Copy the php_mssql.dll from the 'dlls/' directory in distribution package to your windows/system (Win9.x) or winnt/system32 (WinNT, Win2000, XP) directory.

- Add or uncomment the following line under Windows Extentions in your php.ini file (\winnt\php.ini): extension=php_mssql.dll

Hope that helps.
andrew at power-grid dot com
27-May-2004 03:11
Ok, this took me a few days to get right but for those of you out there having a hard time with getting PHP to talk to SQL 2000 this is for you!  Personally for me the mssql plugin barely worked with sql 2000 and was VERY slow, here's your solution and also some good code to connect securely and quickly through ADO. I was having the worst time getting ADO to work as well, most sites do the driver part a different way.. for me the code below is the only thing that worked.
= new COM("ADODB.Connection");
$rs = $db->Execute("SELECT * FROM table");

while (!
Arthur W Rudd
27-May-2004 02:37
I'm running apache 1.3.26 and php 4.3.6 on a linux server (debian), and connecting to SQL Server 2000 via php4-mssql and Freetds.

I managed to get a connection to the SQL server, but found that when I used the function mssql_query() to pass in a Select statement containing datetime columns, I would get the following message in Internet Explorer - "The page cannot be displayed".  When I removed the datetime column from the query, it worked fine, and returned a resultset.
Looked in the apache error.log file, and found the error "child pid xxxxxx exit signal segmentation fault".

After a lot of searching on the internet I stumbled upon an entry which was missing from my php.ini.  I added the line "mssql.datetimeconvert = Off" to the MSSQL section of pphp.ini, restarted Apache, and the problem went away.  Now I can select dates in SQL queries
jasenko at get2net dot dk
06-May-2004 02:46
If you get a crash trying to get currency from database with smallmoney datatype and big value (in my case it was 15000..), change datatype to money instead. The error is gone.

I'm using php 4.2.3 and MSSQL 7.0 on windows.
andrej at dairyweb dot com dot au
28-Apr-2004 04:49
if you are having problems with freeTDS, or like me you are trying to get access to unicode data from mssql.

try http://odbtp.sourceforge.net it is cross platform and (reportedly) faster than freeTDS. it is very stable and easy to configure.

i was originally trying to solve an error message of "Unicode data in Unicode-only collation or ntext data cannot be sent to clients using DB-Library (such as ISQL) or ODBC version 3.7 or earlier" and found this solution.

hope it helps someone.
elmer at web-axis dot net
28-Apr-2004 12:52
Here's something that could save you 2-3 days research trying to figure out:


If you have problems getting the mssql functions to work try these varibles. MSSQL/PHP has problems dealing with different tds versions. 7.0 seems to work well with our server version, maybe a different version would work better with yours.
pmfa at versenet dot com
28-Apr-2004 12:26
If you're going to use freeTDS just to access mssql databases, supply the "--enable-msdblib" switch to the freeTDS configure script when building the library. This will fix some obscure problems, like the month in a date not being displayed correctly, more information in http://www.freetds.org/userguide/config.htm.
gentiboard2002 at yahoo dot de
19-Apr-2004 09:55
there's no documentation of the php.ini option mssql.secure_connection.

so i have here a MS SQL 2000 Server with Windows Authentication and a Windows 2003 Server with IIS 6. So it is clear that i cannot use the usual handling of a mssql_connect.
I turned the mssql.secure_connection on.
I let the Windows IIS to run under an Service Account(normal user account without any special rights) in a Windows Domain, so i do have a authenticated connection to the SQL Server...

Everything works fine without any rewrite of the code...
19-Mar-2004 04:42
Note: DBLib is obsolete and only supports SQL Server 4.x, 6.5, 7.0 and 8.x.
jholland at cs dot selu dot edu
11-Dec-2003 05:37
To enable mssql in php 4.3.3 and above on linux/unix boxes, you must put this line in php.ini