Mssql Functions

Table of Contents

add a note add a note

User Contributed Notes 33 notes

up
2
James at thetallfamily dot com
17 years ago
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
up
2
jigarbe at yahoo dot com
16 years ago
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
up
2
Roy Maarssen
17 years ago
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.
up
1
Sander Wartenberg
16 years ago
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!
up
1
stephan at towli dot ch
14 years ago
I worked on a project with a MS SQL server 2008 containing data of NVARCHAR type in multiple languages,
including asian characters. It is a known issue, that the PHP MSSQL functions are not able to retrieve
unicode data form NVARCHAR or NTEXT data fields.

I spent some time searching for possible solutions and finaly found a work arround, that provides correct
display of latin and asian fonts from a NVARCHAR field.

Do a SQL query, while you convert the NVARCHAR data first to VARBINARY and then to VARCHAR

SELECT
CONVERT(VARCHAR(MAX),CONVERT(VARBINARY(MAX),nvarchar_col)) AS x
FROM dbo.table

While you fetch the result set in PHP, use the iconv() function to convert the data to unicode

<?php $x = iconv("UCS-2LE","UTF-8",$row['x']); ?>

Now you can ouput the text to UTF-8 encoded page with the correct characters.

This workarround did run on IIS 6.0 with PHP 5.2.6 running as FastCGI.
up
1
amolkulkarni82 at gmail dot com
11 years ago
Here is the changes required to connect MSSQL database using  mssql_connect with long password (more than 30 chars)

Steps to follow:

1) cd /usr/local/src/freetds-0.91/

2) Change the values as required in freetds src:

# Default values:
# Filename:  include/sybdb.h (line 67)
#define DBMAXNAME  30

# Filename:  include/tds.h (line 760)
#define TDS_MAX_DYNID_LEN    30

# Filename:  include/tds.h (line 831)
#define TDS_MAX_LOGIN_STR_SZ 30

3) Modify the TDS_MAX_LOGIN_STR_SZ macro to overcome the password limitation of 30 chars

4) Recompile the freetds

make clean && ./configure --prefix=/usr/local/freetds --with-tdsver=8.0 --enable-msdblib --enable-dbmfix --with-gnu-ld && make && make install

5) Restart the apache
/usr/local/apache2/bin/apachectl stop && /usr/local/apache2/bin/apachectl start

6) Export the FREETDS
export FREETDSCONF=/etc/freetds.conf

Test the MSSQLdatabase connection using CLI

> php -a
Interactive mode enabled

<?php

$conn
= mssql_connect('hostname','username','password');

var_dump($conn);

if (!
$conn)
    echo
$strerr = "ERROR: Failed to connect to MSSQL Server ('hostname') : ".mssql_get_last_message();

?>

CTR+D

expected output:

resource(1) of type (mssql link)
up
1
mprentice at eeicom dot com
17 years ago
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
up
1
Bart
18 years ago
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.
up
1
Arthur W Rudd
20 years ago
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
up
0
David Alan
15 years ago
If you get an error like:

PHP Warning:  mssql_query(): message: 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) in /var/www/html/query.php on line 29

There are two solutions: one solution involves casting the data types in the query, the other solution involves changing the version number free tds is using.

The first solution is mentioned all over the web and limits what you can return, the second solution will probably only be found right here. 

Open up your free tds configuration file (/etc/freetds.conf), and change:

[global]
tds version = 4.2

to this:

[global]
tds version = 8.0

You don't have to upgrade any packages, but by default, freetds tries to use an older version (if you installed freetds using yum or apt-get).
up
0
robert dot johnson at icap dot com
16 years ago
There is a PHP driver for SQL Server 2005+ from Microsoft.  You can even download the source code.

Search for "SQL Server 2005 Driver for PHP" on MSDN, or try one of these links:

http://msdn.microsoft.com/en-us/library/cc793139(SQL.90).aspx

http://msdn.microsoft.com/en-us/library/cc296221.aspx
up
0
Keith Radue, South Africa
16 years ago
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
up
0
jigarbe at yahoo dot com
16 years ago
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
up
0
Erwin Moller
16 years ago
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.
up
0
darkelder at php dot net
16 years ago
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.
up
0
ahribernik _at_ blitztelecom com au
17 years ago
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
up
0
nospam at gmail dot com
17 years ago
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.
up
0
hadrien(dot)debris {at} gmail(dot)com
17 years ago
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.
up
0
michael at nospam dot onlinecity dot dk
17 years ago
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.
up
0
chop_01 at yahoo dot com
17 years ago
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>
up
0
swaldester at gmail dot com
17 years ago
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 !
up
0
nmax at libero dot it
17 years ago
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!
up
0
lostaircryptic at hotmail dot co dot uk
17 years ago
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.
up
0
Jason {at} RoundtopRiders {dot} com
17 years ago
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.
up
0
deyura at gmail dot com
17 years ago
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');
up
0
vbchris at gmail dot com
17 years ago
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!

==

[Because this may not always work,] 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");
?>
up
0
ziggurism at gmail dot com
17 years ago
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.
up
0
tom at mazzotta dot com
17 years ago
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.
up
0
be_misc_01 at flowbuzz dot com
17 years ago
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:
<?php $con = mssql_connect ("MyDSN", "MyUserID", "MyPa$$W0rd"); ?>

Will work (single quotes):
<?php $con = mssql_connect ("MyDSN", "MyUserID", 'MyPa$$W0rd'); ?>
up
0
davinel_lu_linvega at hotmail dot com
17 years ago
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]"
up
0
KamiKazie at comcast dot net
18 years ago
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.
up
0
JinXy at skylinetop dot com
18 years ago
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
up
0
anders jenbo(located)pc denmark
18 years ago
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.
To Top