PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

mssql_bind> <Mssql
Last updated: Fri, 22 Aug 2008

view this page in

Mssql Functions

Table of Contents



mssql_bind> <Mssql
Last updated: Fri, 22 Aug 2008
 
add a note add a note User Contributed Notes
Mssql Functions
Keith Radue, South Africa
24-Mar-2008 08:44
My Workstation/server:

Windows 2000 Advanced Server
iis
PHP 5.2.5
SQL server Express

Could not connect using the following connect string:

$sqlconn = mssql_connect "localhost,1433", "user", "password")

After 2 days of frustration and reinstalling PHP + SQLEXPRESS and trying EVERYTHING I could find via Google, I found a setting in PHP.INI that I never noticed.

ENABLE _dl = ON  ---------- I changed this to OFF

Problem went away and all is working as it used to on PHP4

Hope this helps others with the same problem
Sander Wartenberg
05-Mar-2008 02:19
Running on the following settings I couldn't connect to my local SQL server.

- Apache 2.2.6
- PHP 5.2.5
- SQL Server 2005
- Windows XP SP2

The problem lies within the wrong dynamic library that is included in Apache and PHP. To fix this problem follow this steps:

1. Download the good version of ntwdblib.dll (2000.80.194.0)  http://webzila.com/dll/1/ntwdblib.zip
2. Overwrite C:\wamp\bin\apache\apache2.2.6\bin\ntwdblib.dll
3. Overwrite C:\wamp\bin\php\php5.2.5\ntwdblib.dll

4. Start the SQL Server Configuration Manager -> Protocols
5. Enable "named pipes" and "tcp/ip"
6. Right-click "tcp/ip" -> Properties tab "IP addresses"
7. Fill in "TCP Dynamic Ports" with 1433

8. Restart SQL Server AND Apache, PHP and all the other services

Try the following mssql_connect:

mssql_connect('localhost,1433', USERNAME, PASSWORD);

Good luck!
Slartibartfast
21-Feb-2008 07:19
Using Apache on a windows machine to connect to a networked SQL Server I was getting the following error:

Warning: mssql_connect() [function.mssql-connect]: message: Login failed for user 'DomainName\MachineName$'. (severity 14)

This occurred regardless of the username and the password that I passed to mssql_connect()

Apparently the username and password parameters are ignored when connecting to SQL Server with trusted connections. Instead it attempts to connect using the  Web Server username and password instead. Under windows the default webserver account is the machine name (which is probably not set up as being a windows user).

This can be solved by configuring Apache to log on as a designated user.
-    Open Control Panels
-    Double click administrative tools
-    Double click services
-    Right click on Apache and choose properties
-    Under the "Log On" tab choose "This Account" and type in a valid domain user account & password
-    Restart the Apache service
jigarbe at yahoo dot com
15-Feb-2008 06:35
I was able to install and configure Freetds on CENTOS 4 following the guide lines mentioned in beliw mentioned URL

I advice everybody to follow the same

http://members.cox.net/midian/howto/phpMSSQL.htm
jigarbe at yahoo dot com
15-Feb-2008 06:32
PHP and SQL Server

Install And Configure FreeTDS
The first thing you need to do is to download and install the FreeTDS driver. You can get the source and compile it yourself from http://www.freetds.org/, but I prefer RPMs. Depending on your distrobution of Linux, the version you want will vary. I'm running Red Hat Enterprise Linux 4 ES and CentOS 4, which are both almost identical. I installed freetds-0.62.3-1 from http://rpmforge.net/user/packages/freetds/
After installing FreeTDS, you can check your driver by attempting to connect to the MSSQL Server. Of course, use the appropriate server name, username and password in your command line.
# /usr/bin/tsql -S [mssql.servername.or.ip] -U [ValidUser]
locale is "en-US.UTF-8"
locale charset is "UTF-8"
Password: [password]
1>
Enter "quit" to exit your successful connection. If the tsql command doesn't return the 1> prompt, verify that you can get to your MSSQL server with telnet [mssql.servername.or.ip] 1433 and that your username and password are valid.
Next, edit your /etc/freetds.conf configuration file and add the following at the end of the file:
[TDS]
    host = [mssql.servername.or.ip]
    port = 1433
    tds version = 7.0
  Setup ODBC Data Source
Next, unixODBC needs to know about all ODBC drivers you intend to use. While you can use the GUI program that comes with unixODBC, you can also use the odbcinst command. First create a template file containing your FreeTDS setup information.
tdsdriver.template
[FreeTDS]
Description = v.062 with protocol v7.0
Driver = /usr/lib/libtdsodbc.so.0
Run odbcinst, telling it to install a driver entry using the template we just created.
# odbcinst -i -d -f tdsdriver.template
odbcinst: Driver installed. Usage count increased to 1.
    Target directory is /etc
This will add an entry to the end of the file /etc/odbcinst.ini
[FreeTDS]
Description        = v0.62 with protocol v7.0
Driver       = /usr/lib/libtdsodbc.so.0
UsageCount         = 1
Erwin Moller
22-Jan-2008 04:20
Microsoft SQL Server 2005 and Vista.

The following steps enabled MSSQL 2005 support on Vista Home Permium. (native drivers, not odbc which works out-of-the-box)

1) Place ntwdblib.dll in C:\Windows\System32
2) Place php_mssql.dll in C:\Windows\System32
(I gave IUSR full access to these files, maybe read is enough)

3) uncomment php_mssql.dll in php.ini

4) Changed my default SQLSERVER 2005 install so it accepts named piped. (Do this via start-> SQLServer2005->configuration tools->SQL SERVER surface area configuration.

5) reboot.

After that I could use the mssql_* functions.

Hope that helps.
darkelder at php dot net
21-Jan-2008 10:14
Microsoft do offer a SQL Server 2005 driver for PHP at http://www.microsoft.com/sql/technologies/php/default.mspx

It can be download free of charge. Binaries are provided for Windows platform only.
chu61 dot tw at gmail dot com
28-Dec-2007 03:20
To write Unicode (nvarchar) to SQL2000/2005 use PHP
用PHP在SQL Server 存取Unicode資料
----------------------------------------------

Let's assume, we have following data table, that allows us to store unicode values (using UCS-2 encoding):

    create table mytable    (
        myfield nvarchar (100) null
    );

Below is the code to work with:

    $link = mssql_connect('dbhost', 'username', 'password');
    mssql_select_db('database', $link);

    // sending data to database
    $utf8 = 'some unicode UTF-8 data';  // some Greek text for example ;)
    $ucs2 = iconv('UTF-8', 'UCS-2LE', $utf8);

    // converting UCS-2 string into "binary" hexadecimal form
    $arr = unpack('H*hex', $ucs2);
    $hex = "0x{$arr['hex']}";

    // IMPORTANT!
    // please note that value must be passed without apostrophes
    // it should be "... values(0x0123456789ABCEF) ...", not "... values('0x0123456789ABCEF') ..."
    mssql_query("insert into mytable (myfield) values ({$hex})", $link);

    // retrieving data from database
    // IMPORTANT!
    // please note that "varbinary" expects number of bytes
    // in this example it must be 200 (bytes), while size of field is 100 (UCS-2 chars)

    $result = mssql_query("select convert(varbinary(200), myfield) from mytable", $link);

    while (($row = mssql_fetch_array($result, MSSQL_BOTH)))
    {
        // we get data in UCS-2
        // I use UTF-8 in my project, so I encode it back
        echo(iconv('UCS-2LE', 'UTF-8', $row['myfield']));
    }

    mssql_free_result($result);
    mssql_close($link);

--------------------------------------
reference by  etraxis@gmail.com
ahribernik _at_ blitztelecom com au
20-Nov-2007 02:44
FYI if you are on Linux and using FreeTDS for your drivers (you most likely are), you can get past the 255 character limit by:

1. open the file freetds.conf (normally in the directory /etc)
2. under [global] section change the "tds version" to "7.0" or "8.0" (depending on your version of SQL Server)
3. changes should be instant!

use 7.0 for Microsoft SQL Server 7.0
use 8.0 for Microsoft SQL Server 2000 and above

see http://www.freetds.org/userguide/choosingtdsprotocol.htm
nospam at gmail dot com
26-Oct-2007 09:10
If you are using mssql_bind with stored procedures on Windows and need to get around the 255 character varchar limit, one hack is to pass SQLTEXT as the data type to mssql_bind rather than SQLVARCHAR. 

You will still need to use some means to get around returning  varchar data that's longer than 255, the simplest of which is to CAST the varchar field as text in your stored procedure itself.
greg dot thompson at insurity dot com
24-Oct-2007 06:30
There's a note on this page that was helpful:  http://php.net/unpack

See the link for inserting a blob into sql server.
hadrien(dot)debris {at} gmail(dot)com
11-Sep-2007 04:27
I have lost one day to understand why the MSSQL<->PHP connection was no longer functioning after a PHP update (5.2.2->5.2.4).

I eventually found how to solve things:
BEFORE
[code]$link = mssql_connect("SERVER\INST", "LOGIN", "password");[/code]

Which does not work any longer.

AFTER
[code]$link = mssql_connect("SERVER\\INST", "LOGIN", "password");[/code]

Works flawlessly.

Hope that'll prevent someone to lose precious hours of exasperation.
michael at nospam dot onlinecity dot dk
11-Sep-2007 12:55
If you are experiencing that ANSI characters are being corrupted, e.g. nordic letters are showing up as invalid characters and you have SQL Server 2000 installed on the same machine as the webserver, try checking SQL Server Client Network Utility under the DB-Library Options tab.
Make sure that "Automatic ANSI to OEM conversion" is NOT checked, this caused me several hours of headache.
mprentice at eeicom dot com
06-Sep-2007 06:34
It appears ntwdblib.dll is no longer a part of SQL 2005.  According to Microsoft the component is deprecated and they recommend using OLE DB or ODBC.  The dll from SQL Server version 6.5, SQL Server 7.0, or SQL Server 2000 still works against 2005 if you have it.

From Microsoft's site:

 Although the SQL Server 2005 Database Engine still supports connections from existing applications using the DB-Library and Embedded SQL APIs, it does not include the files or documentation needed to do programming work on applications that use these APIs. A future version of the SQL Server Database Engine will drop support for connections from DB-Library or Embedded SQL applications. Do not use DB-Library or Embedded SQL to develop new applications. Remove any dependencies on either DB-Library or Embedded SQL when modifying existing applications. Instead of these APIs, use the SQLClient namespace or an API such as OLE DB or ODBC. SQL Server 2005 does not include the DB-Library DLL required to run these applications. To run DB-Library or Embedded SQL applications you must have available the DB-Library DLL from SQL Server version 6.5, SQL Server 7.0, or SQL Server 2000.
 
http://msdn2.microsoft.com/en-us/library/ms143729.aspx
chop_01 at yahoo dot com
29-Aug-2007 11:38
I tried all manner of things in order to cnnect to SQLExpress aka SQL Server 2005 and was just about to walk away and move across to MySQL when it just dawned on me that after following all of the instructions from numerous people I never restarted the Apache service.

This meant that the new ntwdblib.dll was never called. I restarted the service and hey presto ... I can now connect to the SQL server.

The items that I did were as follows:

1. Installed the SQLServer in mixed auth mode
2. Checked that the mssql.secure_connection = Off was present in the php.ini
3. Copied the ntwdblib.dll file into
        o WINDOWS\SYSTEM32
        o program files\apache2\bin
        o php
4. Started the SQL Server Browser Service
5. Enabled all of the IPs in Protocols > TCP/IP
6. Restarted the following services:
       o Apache
       o SQL Service
       o SQL Browser Service

This allowed me to connect with no problems using the following parameters within my mssql_connect call

HOST=.\SQLEXPRESS
USERNAME=sa
PASSWORD=<MYPASS>
swaldester at gmail dot com
18-Jul-2007 06:03
For all of you connecting to MS SQL Server using freeTDS, having trouble to log on with a domain login:

Add the line:
putenv('TDSVER=70');

just before calling mssql_connect()

This worked for me with a MS SQL Server 2K Ent.

Thank you elmer !
post at wmm dot no
03-Jul-2007 09:48
Having trouble connecting to a MS SQL Server from Windows server with Apache + PHP, or some other server-configuration?

As Tom at mazzotta dot com wrote further down on this page; too old MDAC in Windows may be your problem.

Here is a summary for those working on Windows-plattform:

1. Update your Microsoft MDAC (search for Microsoft Data Access Components on www.microsoft.com). Some older Microsoft servers (or workstations) contain old and crappy MDAC-installations. This solved our problem after two days of work..

2. Make sure ntwdblib.dll (version 8.00.194) is in the correct place(s). I only placed it in Apache bin directory and it worked fine, but apparently some Microsoft installations need it in several locations.. this is indeed very confusing!

3. You may have to set mssql.secure_connection = off in your php.ini

4. Make sure needed ports are configured in your firewall.

Hope this helps - now, back to coffee!
nmax at libero dot it
26-Jun-2007 03:41
About the ntwdblib.dll, I can say that on Windows 2003 Server with Apache 2.2 and PHP 5.2.3 I have repalced the one present in PHP folder with the version 8.00.194 of the same.

Putting the dll only in PHP folder and configuring in php.ini the variable mssql.secure_connection = Off mssql_connect() works!
James at thetallfamily dot com
21-Jun-2007 10:36
MSSQL doesn't have a real_escape_string function like MYSQL does, which can lead to error when inserting or updating data that contains a ' (single quote).

To prevent this, replace all ' (single quotes) by TWO ' (single quotes) '' which SQL server will interpret as an escaped '.
Also you may want to remove any \' \" escape sequences that are translated from any FORM output into the PHP $_POST variables.

Hope this helps someone.
James
hector dot spencer at gmail dot com
18-Jun-2007 03:46
I'm really grateful for saving me hours, if not days in trying to make PHP work with SQLServer database, Thanks a lot and I'll make sure to make a not so overwhelming and friendly tutorial for spanish speakers. Thanks a lot mate!
Roy Maarssen
07-May-2007 11:47
My problem was that I've loaded the ntwdblib.dll (8.00.194) into the php directory, but it also have to be placed in the bin directory of Apache.

I hope this will save you some time searching for the solution, if you encounter the same problem.

I'm using SQL 2005 Express Edition on Windows Vista Enterprise with Apache.
lostaircryptic at hotmail dot co dot uk
30-Apr-2007 01:34
MAXIMUM COLUMN LENGTH OF 30 CHARACTERS....

This restriction was solved by using the following techniques.

First create a test which detects this to be the problem and then self correct it.

For the times that this is a problem rename the columns to an unique column name which is 30 characters exactly in length.  This column must be unique compares to the others, so use the MD5 Hashed value.  Since MD5 hashed values are 32 character HEX values, convert this to a toggle Hex value giving an exact maximum length of 31 characters.  Prepend a character to the start to ensure that it falls within Column naming regulations.

When the data is obtained, check for the hashed values against a check array and replace where neccessary.

Although complex it may sound, the method has been tried and successfully works, thus allowing columns of greater length than that of 30 characters.

I had this situation within Linux as well as Windows (XAMPP), so this solution was ultimate in solving the problem.

You can run the detection as a constant or automatically.  However it is best to use a constant for efficiency reasons.

Any questions, just email me.
vbchris at gmail dot com
24-Apr-2007 11:22
My previous post although seemed to solve the problem of the connection randomly refusing to connect, it didn't. This however did. I created a loop to create a few connections and noticed it was always the first connection that failed. So I wrote this to keep trying to connect until it eventually does.

<?php
while(!$connection){
    @
$connection = mssql_connect($cfg['server'],$cfg['username'],$cfg['password']);
}
$db = mssql_select_db($cfg['database'],$connection) or die("Error selecting the database");
?>
Jason {at} RoundtopRiders {dot} com
10-Apr-2007 09:54
I struggled with this for a few days and finally got it figured out. I'm running Windows 2003 Server, PHP 5.2, Apache 2.2 and MSSQL Server 2005.

(1) Set 'msssql.secure_connection = On' in the PHP.ini file
(2) Download the correct ntwdblib.dll file (version 8.00.194)

Copy this to:

C:/Windows/System32
<server root>/php
<server root>/apache/bin

(I would just do a search for this file and replace it anywhere you find it...)

(3) Make sure TCP/IP and Named Pipes are enabled in the SQL Configuration tool.

Hope this saves somebody a few hours.
deyura at gmail dot com
10-Apr-2007 01:06
FreeTDS is work!!!

But after install you shoul add in config file
1. Add in freetds.conf client cahrset:
[TDS_NAME_TO_CONNECT]
host = 192.168.0.1
port = 1433
tds version = 8.0
client charset = CP1251

2. For datetime add in locales.conf in [default]:
date format = %Y-%m-%d %I:%M:%S.%z

3. restart apache

4. In your php-script you should connect to [TDS_NAME_TO_CONNECT]
mssql_connect('TDS_NAME_TO_CONNECT', 'php', '123');
deyura at gmail dot com
10-Apr-2007 01:05
FreeTDS is work!!!

But after install you shoul add in config file
1. Add in freetds.conf client cahrset:
[TDS_NAME_TO_CONNECT]
host = 192.168.0.1
port = 1433
tds version = 8.0
client charset = CP1251

2. For datetime add in locales.conf in [default]:
date format = %Y-%m-%d %I:%M:%S.%z

3. restart apache

4. In your php-script you should connect to [TDS_NAME_TO_CONNECT]
mssql_connect('TDS_NAME_TO_CONNECT', 'php', '123');
vbchris at gmail dot com
06-Apr-2007 06:56
If your having problems with  your script at random times refusing to connect to the database. Try editing php.ini and uncommenting this line.

mssql.max_procs = -1

This solved the problem for me after 3 days of pulling my hair out wondering why it kept refusing to connect!
ziggurism at gmail dot com
30-Jan-2007 08:53
On *nix, of course you need to add extension=mssql.so to your php.ini.  Obvious, but it took me a while to figure that out.
tom at mazzotta dot com
19-Jan-2007 01:38
FINNALLY got PHP to connect to MS SQL Server. Even though I read through the multitue of comments about ntwdblib.dll, etc., I still couldn't get it to work. The key was to load the Microsoft MDAC (2.8) on my IIS/PHP server. If your environement does not use the web server to host SQL as well, you will probably need to install the MDAC. My guess is that an installation of SQL Server (and/or just the client tools) on the webserver will automatically include the MDAC and you would not experience this problem.
phpnet at pginet dot com
08-Jan-2007 10:35
This took me a while to figure out, so I may as well pass it along to save somebody time.

If you are having trouble connecting with a DSNless connection using unixodbc with freetds, don't forget to specify the TDS_Version in your connection string.

Example (8.0 is for SQL Server 2000 exclusively):

$dsn = "DRIVER=FreeTDS;TDS_Version=8.0; TRACE=No; SERVER=someserver; PORT=someport; DATABASE=somedb; UID=somelogin; PWD=somepassword";
be_misc_01 at flowbuzz dot com
20-Dec-2006 11:06
Couple of notes:
When setting this up, you might notice that the unixODBC isql command likes the password wrapped in single quotes:
isql -v MyDSN MyUserID 'MyPa$$W0rd'

Additionally, if you happen to have a dollar-sign in your password (or username, or DSN) -- you must avoid using double quotes.  This is a normal PHP gotcha, but worth mentioning.
Won't work:
$con = mssql_connect ("MyDSN", "MyUserID", "MyPa$$W0rd");

Will work (single quotes):
$con = mssql_connect ("MyDSN", "MyUserID", 'MyPa$$W0rd');
davinel_lu_linvega at hotmail dot com
07-Dec-2006 01:38
About using the MSSQL XML field-type, for Win32 users,  :

1. The most simple way would be to

"SELECT [xmlfield] FROM [table]"

But this triggers the following error :

"Unicode data in a Unicode-only collation or ntext data cannot be sent to clients using DB-Library (such as ISQL) or ODBC version 3.7 or earlier. (severity 16)"

2. Well, let's just read [xmlfield] as a VARCHAR.

"SELECT CAST([xmlfield] AS VARCHAR(8000)) FROM [table]"

will truncate to the 255 first characters, due to the API limitation. (see the marc at NOSPAM dot durdin dot net note)

3. So woud not that be appropriate to use the TEXT field-type ?

"SELECT CAST([xmlfield] AS TEXT) FROM [table]"

triggers :

"Explicit conversion from data type xml to text is not allowed. (severity 16)"

4. So you cannot read the VARCHAR nor the XML, and you cannot transform the XML into TEXT. In order to finally read that XML field-type, you may use this trick :

"SELECT CAST(CAST([xmlfield] AS VARCHAR(8000)) AS TEXT) FROM [table]"
KamiKazie at comcast dot net
22-Nov-2006 05:01
I have found that a Windows Webserver cannot connect to a Microsoft SQL Database if the webserver is running Microsoft SQL Server Agent.  It gives connection and undefined function errors.  Hope this helps some people.
JinXy at skylinetop dot com
15-Nov-2006 06:37
I had major problems trying to get the msssql extension loaded.  The following fixed it for me: 

1. Make sure the ntwdblib.dll file located in system32/ on the Database server is copied to system32 on the PHP serving server.
2. Uncomment the extension in the php.ini file.
3. Add the following to the registry: [HKEY_LOCAL_MACHINE\SOFTWARE\PHP]
"IniFilePath"="C:\\PHP"
This tells PHP where to find the php.ini
(This is what my resolution to my problem was - only after some time did I find some reference to it).
4. Restart IIS
anders jenbo(located)pc denmark
03-Nov-2006 10: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
19-Sep-2006 07: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 04: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 03: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.
Bart
22-May-2006 07: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 12:13
mssql.datetimeconvert

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

removed
ini_set('mssql.datetimeconvert',false);
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 11: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 05: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
08-Dec-2005 06: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 01: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 02: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 04:58
Some helpful functions.  Pretty simple, but very useful.

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

function mssql_commit() {
  mssql_query("COMMIT");
}

function mssql_rollback() {
  mssql_query("ROLLBACK");
}

function mssql_insert_id() {
  $id = "";

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

  return $id;
}
vangoethem at hotmail.com
10-Aug-2005 03: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 12: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.
cmeerbeek[at]ymor[.]nl
13-May-2005 11: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 06:42
Hello!

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

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

  while (!
$rs->EOF)
  {
     echo
$rs->Fields['name']->Value."<BR>";
    
$rs->MoveNext();
  }
?>

Diego Bandeira.
boonkit at gmail dot com
29-Mar-2005 12: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
tony
23-Mar-2005 05: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 08: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
25-Jan-2005 07: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
25-Jan-2005 07: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.

mssql_connect(dsn,uid,pwd);

it worked well
craig at _NO_SPAM_deconstructor dot net
13-Jan-2005 10: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"
Password:
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
=======================================
         to
=======================================
./configure --prefix=/usr/local
=======================================

Small but worth noting.
hbinduni at hslprpol dot com
20-Dec-2004 10: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 06: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)
   SELECT CAST(MyVarCharField AS TEXT) FROM MyTable
ASWL
28-Oct-2004 03: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)
24-Oct-2004 10: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

http://phprpms.sf.net/mssql
effeese at gmail dot com
15-Oct-2004 04: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):
<?
$db
= new COM("ADODB.Connection");
$dsn = "DRIVER={SQL Server}; SERVER={SERVER};UID={USER};PWD={PASS}; DATABASE={DB}";
$db->Open($dsn);
$rs = $db->Execute("SELECT * FROM table");

while (!
$rs->EOF)
{
   echo
$rs->Fields['column']->Value."<BR>";
  
$rs->MoveNext();
}
?>

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

<?
    putenv
('FREETDSCONF=/etc/freetds.conf');

    
/*
        mssql_connect('MSSQL_8.0' , 'user' , 'pwd');
        ....
        ....
    */
?>

FreeTDS conf file

 [MSSQL_8.0]
    host = 10.254.254.10
    port = 1433
    tds version = 8.0
08-Aug-2004 01: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 01: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.

INSTALLING FREETDS
 
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 198.168.100.2 -U sa

8-.  Add the next text in freetds.conf ( /usr/local/freetds/etc )
[TDS]
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
/usr/local/freetds/lib

INSTALLING  APACHE

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

INSTALLING  PHP

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

TESTING

<html>
<body>
<?php
$con
= mssql_connect ("<ip of the server SQL>", "sa", "");
mssql_select_db ("<Data Base>", $con);
$sql= "SELECT * FROM <Table>";
$rs= mssql_query ($sql, $con);
echo
"The field number one is: ";
echo
mssql_result ($rs, 0, 0);
mssql_close ($con);
?>
</body>
</html>
Asad Moin
29-May-2004 05: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
26-May-2004 10: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.
<?
$db
= new COM("ADODB.Connection");
$dsn = "DRIVER={SQL Server}; SERVER={SERVER};UID={USER};PWD={PASS}; DATABASE={DB}";
$db->Open($dsn);
$rs = $db->Execute("SELECT * FROM table");

while (!
$rs->EOF)
{
    echo
$rs->Fields['column']->Value."<BR>";
   
$rs->MoveNext();
}
?>
Arthur W Rudd
26-May-2004 09: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
05-May-2004 09: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 11: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 07:52
Here's something that could save you 2-3 days research trying to figure out:

<?php
putenv
('TDSDUMP=/tmp/tds.log');
putenv('SYBASE=/usr/lib/freetds');
putenv('TDSVER=70');
?>

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
27-Apr-2004 07: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 04: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 10: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
10-Dec-2003 11:37
To enable mssql in php 4.3.3 and above on linux/unix boxes, you must put this line in php.ini

extension=mssql.so

mssql_bind> <Mssql
Last updated: Fri, 22 Aug 2008
 
 
show source | credits | sitemap | contact | advertising | mirror sites