PHP

Connecting to MSSQL

The Microsoft SQL engine comes in two flavors: the fully featured (and fully priced) Microsoft SQL Server (short: MSSQL) and the free edition, the Microsoft SQL Server Desktop Engine (short: MSDE), available for free at http://www.asp.net/msde/. Both versions are supported by PHP because they are compatible to each other.

@mssql_connect()

To make it work, you need the line extension=php_mssql.dll in your php.ini. Also, PHP needs access to the client libraries for MSSQL/MSDE, the file ntwdblib.dll. In PHP 5, this file is in the PHP directory, so the PHP process just needs read access to it. In PHP 4, you might have to copy the file (that resides in the dll subdirectory) somewhere else, for example in the Windows system32 folder.

However, UNIX/Linux systems can also connect to MSSQL/MSDE installations in a heterogenous network, a combination that powers some high-traffic websites. For this to work, you have to download the FreeTDS library from http://www.freetds.org/ and install it after unpacking the distribution with this command:

./configure prefix=/usr/local/tds with-tdsver= 4.2 make
sudo make install

Then, reconfigure PHP with the switch with-sybase=/usr/local/freetds.

Finally, you can connect to the server using mssql_connect() and select the database to be used using mssql_select_db(), as the preceding listing shows.

Connecting to MSSDE/MSDE

<?php
  if ($db = @mssql_connect('localhost', 'user',
    'password')) {
    mssql_select_db('hoshmand');
    echo 'Connected to the database.';
    mssql_close($db);
  } else {
    echo 'Connection failed.';
  }
?>

MSSQL/MSDE supports two modes to authenticate users: SQL authentication and Windows authentication. The latter one checks whether the current Windows user has sufficient rights to access the database. In a controlled environment, this might be a better idea than using username and password. However, you first have to find out which user is used. For instance, Microsoft IIS web server software uses the Internet guest account, that is, IUSR_<machinename>. Therefore, this user requires privileges in the database.

To use Windows authenticationsometimes also called trusted connectionyou need the following php.ini directive:

mssql.secure_connection = On

by BrainBellupdated
Advertisement: