Accessing Microsoft SQL Server (mssql) from PHP under Apache on Unix or Linux

PHP is an open-source scripting language used to create database-driven web applications. PHP supports a number of database extensions that enable PHP scripts embedded within web pages to access data stored in relational databases and display the results. PHP includes ODBC support through its Unified ODBC database extension.

This tutorial shows you how to use ODBC to access remote SQL Server databases from PHP scripts running under the Apache web server.

Connect PHP to SQL Server 2000, SQL Server 2005, SQL Server 2008, SQL Server 2012, SQL Server 2014, SQL Server 2016, SQL Server 2017, SQL Server 2019 and SQL Server Express

When developing this tutorial, we accessed SQL Server 2000–2019 and Express databases from PHP on UNIX and Linux.

PHP and Linux

To access SQL Server from PHP on Linux, we used Easysoft ODBC drivers with PHP on RedHat and Ubuntu (Edgy Eft, Feisty Fawn, Gutsy Gibbon and Hardy Heron). Easysoft ODBC drivers should work with any recent 32-bit or 64-bit Linux distribution—CentOS, Debian GNU/Linux, Fedora, Kubuntu, Mandrake/Mandriva, OpenSUSE/SUSE, RedHat Enterprise Linux (RHEL), Slackware and so on.

PHP SQL Server Pre-requisites

To connect PHP on UNIX/Linux with SQL Server, we used:

PHP 4.2 or Later

To check which version of PHP you are running, use the php -v command from the shell prompt.

If you get a "command not found" error, there is no PHP on your PATH (perhaps because you have not installed it). If PHP is installed, you should see something like "4.2.2".

If you have an older version of PHP than the required one, go to http://www.php.net, and get an up to date distribution. Documentation and installation instructions can be found both in the README that is included in the distribution and at http://www.php.net/docs.php.

We tested Easysoft ODBC drivers with PHP 5.4.5, PHP 5.3.10, PHP 5.2.3 and PHP 4.2.2.

Installing PHP

We used a package manager to install PHP on our Linux client machines. A package manager is a program that installs and uninstalls software, and keeps track of the components each piece of software needs. On Ubuntu, we used the Synaptic package manager to install PHP. On RedHat, we used the redhat-config-packages package manager to install PHP from RPMs.

Installing PHP from Packages on Ubuntu

  1. On the System menu, choose Administration, and then choose Synaptic Package Manager.
  2. Type the administrative (sudo) password when prompted.
  3. In Synaptic Package Manager, mark php5 and php5-odbc for installation.

    Accept when prompted to install dependent packages (libapache2-mod-php5, php5-common and unixodbc).

  4. If you want to run PHP from the command line as well as from under Apache, mark php-cli for installation.
  5. Click the Apply button.

Installing PHP from RPMs on RedHat

  1. Click the RedHat icon, and then click Add/Remove Applications from the System Settings menu.
  2. Type the root password when prompted.
  3. Add the php and php-odbc Web Server packages.
  4. Click the Update button.

Testing PHP

The first PHP script you create should call the phpinfo function, as this function allows you to test that your PHP distribution is working correctly. The phpinfo function displays extensive configuration information about PHP and the system on which PHP is running. To create this PHP script, you need to do something like this:

  1. Create a file called phpinfo.php.
  2. Add these lines to phpinfo.php:
    #!/bin/bash
    # This is a simple one liner that amongst other things returns relevant PHP information
    <?php
        phpinfo()
    ?>
    
  3. Save this file, and then from the command line, type:
    php phpinfo.php > newhtmlfile.html 
    

    This redirects the output from phpinfo into an HTML file called newhtmlfile.html.

Apache 2.0 or Later

When developing this tutorial, we ran PHP under Apache 2.4, Apache 2.2 and Apache 2.0. To find out which version of Apache you are running, enter the following command at the shell prompt:

httpd_bin_dir/httpd -V

–Or–

httpd_bin_dir/apache2 -V

where httpd_bin_dir is the directory where the http daemon is installed. For example, on Linux, the default location is normally /usr/sbin. The -V option displays information about the Apache installation. For example:

Server version: Apache/2.2.4 (Ubuntu)
Server built:   Oct  4 2007 22:47:20
Server's Module Magic Number: 20051115:5
Server loaded:  APR 1.2.7, APR-Util 1.2.7
Compiled using: APR 1.2.7, APR-Util 1.2.7
Architecture:   32-bit
Server MPM:     Prefork
  threaded:     no
    forked:     yes (variable process count)
Server compiled with....
 -D APACHE_MPM_DIR="server/mpm/prefork"
 -D APR_HAS_SENDFILE

On Ubuntu, make sure that /etc/apache2/apache2.conf contains an entry similar to:

LoadModule php5_module modules/libphp5.so

The entry enables Apache to dynamically load the PHP module.

On RedHat, check /etc/httpd/conf.d/php.conf for this entry.

We created both .php and .phtml sample files for this tutorial. To tell Apache which module it should use to process the .php and .phtml files, we added this entry to the Apache httpd.conf file (apache2.conf on Ubuntu):

# Use the PHP module to process .php and .phtml files.
AddType application/x-httpd-php .php .phtml

Note All the examples in this tutorial will work even if you do not have a web server installed. You can also run the example PHP scripts from the shell prompt.

SQL Server ODBC Driver

We used our UNIX/Linux ODBC driver for SQL Server 7.0, 2000, 2005, 2008, 2012, 2014, 2016, 2017, 2019 and Express to connect PHP to remote SQL Server databases.

  1. Download the SQL Server ODBC driver for your PHP client platform. (Registration required.)

    If the SQL Server ODBC driver is not currently available for your platform, check the list of ODBC-ODBC Bridge Client platforms. The ODBC-ODBC Bridge is an alternative SQL Server solution from Easysoft, which you can download from this site.

  2. Install and license the SQL Server ODBC driver on the machine where PHP is installed.

    For installation instructions, see the ODBC driver documentation. Refer to the documentation to see which environment variables you need to set (LD_LIBRARY_PATH, LIBPATH, LD_RUN_PATH, SHLIB_PATH depending on the driver, platform and linker).

  3. Create an ODBC data source in /etc/odbc.ini that connects to the SQL Server database you want to access from PHP. For example, this SQL Server ODBC data source connects to a SQL Server Express instance that serves the Northwind database:
    [MSSQL-PHP]
    Driver                  = Easysoft ODBC-SQL Server
    Server                  = my_machine\SQLEXPRESS
    User                    = my_domain\my_user
    Password                = my_password
    # If the database you want to connect to is the default
    # for the SQL Server login, omit this attribute
    Database                = Northwind
    
  4. Use isql to test the new data source. For example:
    cd /usr/local/easysoft/unixODBC/bin
    ./isql -v MSSQL-PHP
    

    At the prompt, type "help" to display a list of tables. To exit, press return in an empty prompt line.

Examples: How to Connect PHP with SQL Server and Retrieve Data

The following PHP script accesses a remote SQL Server database, selects and then fetches some test data. Use it to check that you can successfully access your SQL Server instance from a PHP script. Remember to replace the data_source_name and database username and password placeholders with appropriate values for your database.

To run this script:

  1. Copy the script shown below into a new file.
  2. Replace data_source_name, database_username and database_password with your SQL Server ODBC data source, login name and password.
  3. To run the script under Apache, save the file below your Apache web server’s document root directory. For example, /var/www/apache2-default/php-mssql-connection.phtml. Then view the file in a web browser:

    http://localhost/php-mssql-connection.phtml

    If your web browser is not running on the same machine as the web server, replace localhost with the web server’s host name or IP address.

  4. To run the script from the command line, save the file. For example, /tmp/php-mssql-connection.php. Then run $ php /tmp/php-mssql-connection.php.
<?php
/*
PHP MSSQL Example

Replace data_source_name with the name of your data source.
Replace database_username and database_password
with the SQL Server database username and password.
*/
$data_source='data_source_name';
$user='database_username';
$password='database_password';

// Connect to the data source and get a handle for that connection.
$conn=odbc_connect($data_source,$user,$password);
if (!$conn){
    if (phpversion() < '4.0'){
      exit("Connection Failed: . $php_errormsg" );
    }
    else{
      exit("Connection Failed:" . odbc_errormsg() );
    }
}

// This query generates a result set with one record in it.
$sql="SELECT 1 AS test_col";

# Execute the statement.
$rs=odbc_exec($conn,$sql);

// Fetch and display the result set value.
if (!$rs){
    exit("Error in SQL");
}
while (odbc_fetch_row($rs)){
    $col1=odbc_result($rs, "test_col");
    echo "$col1\n";
}

// Disconnect the database from the database handle.
odbc_close($conn);
?>

Our next example PHP script uses the odbc_tables function to list the tables in a SQL Server database. To run this script:

  1. Copy the script shown below into a new file.
  2. Replace data_source_name, database_username and database_password with your SQL Server ODBC data source, login name and password.
  3. Save the file below your Apache web server’s document root directory. For example, /var/www/apache2-default/mssql-php-retrieve-data.phtml.
<html>
<head>
<title>MSSQL PHP Example -- Table List</title>
</head>
<body>
<?php
/*
This script will list all the tables in the specified data source.
Replace datasource_name with the name of your data source.
Replace database_username and database_password
with the SQL Server database username and password.
*/
$data_source='data_source_name';
$user='database_username';
$password='database_password';

// Connect to the data source and get a handle for that connection.
$conn=odbc_connect($data_source,$user,$password);
if (!$conn){
    if (phpversion() < '4.0'){
      exit("Connection Failed: . $php_errormsg" );
    }
    else{
      exit("Connection Failed:" . odbc_errormsg() );
    }
}

// Retrieves table list.
$result = odbc_tables($conn);

   $tables = array();
   while (odbc_fetch_row($result))
     array_push($tables, odbc_result($result, "TABLE_NAME") );
// Begin table of names.
     echo "<center> <table border = 1>";
     echo "<tr><th>Table Count</th><th>Table Name</th></tr>";
// Create table rows with data.
   foreach( $tables as $tablename ) {
     $tablecount = $tablecount+1;
     echo "<tr><td>$tablecount</td><td>$tablename</td></tr>";
   }

// End table.
echo "</table></center>";
// Disconnect the database from the database handle.
odbc_close($conn);
?>
</body>
</html>

Note The PHP script shown above uses an HTML table to lay out the results. The script is wrapped in HTML therefore and is intended to be run under the Apache web server. If you want to run the script from a shell prompt:

  1. Copy the script shown below into a new file.
  2. Replace datasource_name, database_username and database_password with your SQL Server ODBC data source, login name and password.
  3. Save the file. For example, /tmp/mssql-php-retrieve-data.php.
  4. Run the script from the command line. For example $ php /tmp/mssql-php-retrieve-data.php.
<?php
/*
MSSQL PHP Example

This script will list all the tables in the specified data source.
Replace datasource_name with the name of your data source.
Replace database_username and database_password
with the SQL Server database username and password.
*/
$data_source='datasource_name';
$user='database_username';
$password='database_password';

// Connect to the data source and get a handle for that connection.
$conn=odbc_connect($data_source,$user,$password);
if (!$conn){
    if (phpversion() < '4.0'){
      exit("Connection Failed: . $php_errormsg" );
    }
    else{
      exit("Connection Failed:" . odbc_errormsg() );
    }
}

// Retrieves table list.
$result = odbc_tables($conn);

   $tables = array();
   while (odbc_fetch_row($result))
     array_push($tables, odbc_result($result, "TABLE_NAME") );
// Begin table of names.
     echo "Table Count  Table Name\n";
# Create table rows with data.
   foreach( $tables as $tablename ) {
     $tablecount = $tablecount+1;
     echo "$tablecount            $tablename\n";
   }

// Disconnect the database from the database handle.
odbc_close($conn);
?>

Example: How to Call SQL Server Procedures from PHP

The following section shows you how to create and call SQL Server procedures from PHP.

To use the sample script, you need a SQL Server database in which you can create and delete procedures. The data source that you specify in the scripts needs to connect to this database.

Here is a simple procedure that runs a SELECT statement and returns the results.

<?php
/*
MSSQL PHP Example

Replace datasource_name with the name of your data source.
Replace database_username and database_password
with the SQL Server database username and password.
*/
  $data_source ='datasource_name';
  $user = 'database_username';
  $password = 'database_password';

// Connect to the data source and get a handle for that connection.
  $conn = odbc_connect($data_source,$user,$password,SQL_CUR_DEFAULT);
  if (!$conn){
    if (phpversion() < '4.0'){
    exit("Connection Failed: . $php_errormsg" );
    }
    else{
    exit("Connection Failed:" . odbc_errormsg());
    }
  }

// This procedure simply calls the select statement used in the initial code sample
  $sp = "CREATE PROCEDURE PROCEDURE_TEST AS
       SELECT 1 AS test_col";
// Prepare the statement
  $stmt = odbc_prepare($conn,$sp);
// Execute the statement.
  odbc_execute ($stmt);

  $callsp = "{call PROCEDURE_TEST}";
  $stmt = odbc_prepare($conn,$callsp);
  $parms = array();

  @odbc_execute ($stmt, $parms);

// Output the procedure's return value.
  odbc_result_all($stmt);

// Drop the precedure
  $dropsp = "DROP PROCEDURE PROCEDURE_TEST";
  $stmt = odbc_prepare($conn,$dropsp);

  odbc_execute ($stmt);
// Disconnect the database from the database handle.
  odbc_close($conn);
?>

PHP Data Objects (PDO)

The PHP Data Objects (PDO) extension provides an object oriented data access abstraction layer, which enables you to use the same PHP code to execute SQL queries, fetch data, and so on, regardless of which database you are using. PDO was initially released as an extension for PHP 5.0 on the PHP Extension Community Library (PECL). PDO is included in PHP 5.1+. Because PDO requires the object oriented features introduced in PHP 5.0, it will not work with earlier versions of PHP.

PDO supports:

The PDO architecture has two levels. The top level, PDO, provides a database independent interface for interacting with databases. The lower level consists of database-specific drivers, which translate between the top level interface and the relevant database interface (for example, ODBC or OCI). The PDO architecture insulates your PHP applications and scripts from database-specific details letting you switch from one database to another without having to change your PHP code.

The PDO_ODBC driver enables you to access ODBC databases via the PDO interface. PDO_ODBC supports the unixODBC Driver Manager, which it uses to load the ODBC driver for the target database. PDO_ODBC can be used with the SQL Server ODBC driver to enable PDO access to SQL Server from Linux and Unix platforms.

Installing the SQL Server ODBC Driver

You need to install the SQL Server ODBC driver on the machine where PHP is installed. For information about installing the SQL Server ODBC driver, see earlier in this tutorial.

Installing PDO and PDO_ODBC

We tested the SQL Server ODBC driver with PDO / PDO_ODBC using:

Installing from Packages

Most Linux distributions enable you to install PHP modules via their Package Managers (Synaptic, Yum and so on). When testing on Ubuntu Linux, we installed the following packages:

Package Notes
php5-cli Enables PHP scripts to be run standalone. Automatically supports PDO.
php5-odbc Includes the PDO_ODBC driver (and the Unified ODBC database extension). Installs PDO_ODBC as a shared object, which the package installer configures PHP to load automatically by adding an entry to php.ini.
libodbc1 The version of PDO_ODBC included in the php5-odbc package is built to support the unixODBC Driver Manager. The libodbc1 package contains the unixODBC libraries and is a dependent package of php5-odbc.
apache2-mpm-prefork Apache HTTP server. This is the non-threaded version as libapache2-mod-php5 is not compatible with the threaded version of Apache (apache2-mpm-worker).
libapache2-mod-php5 PHP module for Apache. Automatically supports PDO. Enables PHP to be run under Apache. The Apache HTTP server was automatically configured to load this module and use this module for pages with a .php or .phtml extension. No additional configuration was necessary.

Building from Source

By default, PDO is automatically built into the PHP 5.1+ binary, and so you do not need to configure the PHP build system to get PDO support.

To build PDO_ODBC, you need to include the --with-pdo-odbc option on the configure line. (For other configure options, type ./configure --help.) To use PDO_ODBC with the SQL Server ODBC driver, you need to build PDO_ODBC with unixODBC support. To do this, set the --with-pdo-odbc option's value to unixODBC.

To build PDO_ODBC with unixODBC support, PDO_ODBC needs to find the unixODBC libraries and header files. By default, the PHP build system expects unixODBC to be installed under /usr/local. The unixODBC Driver Manager included in the SQL Server ODBC driver distribution is installed under installation_dir/easysoft/unixODBC, where installation_dir is the Easysoft installation directory, by default, /usr/local. To build PDO_ODBC against this version of unixODBC (which is the one the SQL Server ODBC driver has been tested with), include this path in the --with-pdo-odbc option's value.

PDO_ODBC can be built as either a static (the default, which means that your PHP Apache module or PHP binary will be statically linked against PDO_ODBC) or a shared module. To build PDO_ODBC as a shared module, specify shared in the --with-pdo-odbc option's value.

In the following example, PDO_ODBC is built as a shared module against the unixODBC included in the SQL Server ODBC driver distribution:

# cd php-5.4.5
# ./configure --with-pdo-odbc=shared,unixODBC,/usr/local/easysoft/unixODBC
# make
# make install

Notes

Connecting to SQL Server through PDO

To use the PDO interface to connect to SQL Server via ODBC, in your PHP script, call new PDO() to create a database handle object:

$dbh = new PDO(PDO_ODBC_DSN);

where PDO_ODBC_DSN has the following format:

odbc:DSN

–Or–

odbc:connection_string

You can either specify an ODBC DSN (defined in a file such as /etc/odbc.ini) or a DSN-less connection after the odbc: prefix. For example:

$dbh = new PDO('odbc:MY_MSSQL_DSN');

–Or–

$dbh = new PDO('odbc:DRIVER={Easysoft ODBC-SQL Server};SERVER=mymachine\sqlexpress;UID=mydomain\myuser;PWD=mypassword')

You can supply the user name and password as arguments in the PDO() call (for example, because you do not want to store them in odbc.ini):

$dbh = new PDO('odbc:MY_MSSQL_DSN', 'mydomain\myuser', 'mypassword');

You can also connect to a PDO_ODBC DSN defined in php.ini. If you specify just the PDO_ODBC DSN name in your PDO() call (with no prefix), PDO will look in php.ini for pdo.dsn.name. For example:

$dbh = new PDO('MSSQL');
; PDO_ODBC DSN defined in php.ini
pdo.dsn.MSSQL=odbc:MY_MSSQL_DSN

If your connection fails with the error Error!: could not find driver, use the phpinfo function to output the configure line for your version of PHP. If the configure line does not contain the --with-pdo-odbc option, PDO_ODBC is not installed. If the --with-pdo-odbc option value contains shared, check that php.ini is loading PDO_ODBC.

Example: How to Connect PDO_ODBC with SQL Server and Retrieve Data

<?php
/*
PDO_ODBC MSSQL Example

Replace <DSN> with the name of your ODBC data source.

*/
$dsn ="odbc:<DSN>";

try {

    // Connect to the data source and get a database handle for that connection.
    $dbh = new PDO($dsn);
    $stmt = $dbh->prepare("SELECT 1 AS test_col");
    $stmt->execute();
    while ($row = $stmt->fetch()) {
      print_r($row);
    }
    $stmt = NULL;
    $dbh = NULL;

} catch (PDOException $e) {
   echo "Failed to connect: " . $e->getMessage();
}
?>

Example: How to Retrieve SQL Server Procedure Output Parameters from PHP

A SQL Server stored procedure can return information by using either a RETURN statement or one or more output parameters. A RETURN statement enables a stored procedure to return an integer value, which reports the execution status of the procedure. Output parameters enable procedures to return other types of values, for example, character strings.

PDO, unlike the Unified ODBC extension, provides direct support for output parameters. This section contains an example that calls a stored procedure from PHP and retrieves an output parameter value. (To retrieve procedure output parameters by using the Unified ODBC extension a workaround is required.)

<?php
/*
PDO_ODBC MSSQL Procedure Output Parameters Example

To run this example, specify the AdventureWorks sample database
when connecting to SQL Server. The user you specify for the
connection needs to be able to create procedures in this
database.

Replace <DSN> with the name of your ODBC data source.
*/
$dsn ="odbc:<DSN>";

try {
    $dbh = new PDO($dsn);

    /*
    This procedure returns the year to date sales for a specified employee.
    The employee is specified with an input parameter. The YTD sales are
    returned with an output parameter.
    */
    $stmt = $dbh->prepare("CREATE PROCEDURE GetEmployeeSalesYTD
                         @SalesPerson nvarchar(50),
                         @SalesYTD money OUTPUT
                         AS
                         SELECT @SalesYTD = SalesYTD
                         FROM Sales.SalesPerson AS sp
                         JOIN HumanResources.vEmployee AS e
                         ON e.EmployeeID = sp.SalesPersonID
                         WHERE LastName = @SalesPerson");

    $stmt->execute();

    // The employee to return the YTD sales for.
    $inval = "Blythe";
    $outval = 0;

    $stmt = $dbh->prepare("{call GetEmployeeSalesYTD( ?, ? )}");

    $stmt->bindParam(1, $inval, PDO::PARAM_STR);

    /*
    To indicate that a parameter is an OUTPUT parameter, you must explicitly
    set the length.
    */
    $stmt->bindParam(2, $outval, PDO::PARAM_STR, 20);
    $stmt->execute();

    // Display the value of the output parameter.
    print "YTD sales for ".$inval." are ". $outval. ".";

    $stmt = $dbh->prepare("DROP PROCEDURE GetEmployeeSalesYTD");
    $stmt->execute();

    $stmt = NULL;
    $dbh = NULL;

} catch (PDOException $e) {
   echo "Failed to connect:" . $e->getMessage();
}
?>

Alternative PHP and SQL Server Solution

The ODBC-ODBC Bridge is another solution from Easysoft that provides PHP to SQL Server connectivity from UNIX and Linux platforms.

The ODBC-ODBC Bridge is available on more platforms than our SQL Server ODBC driver.

The ODBC-ODBC Bridge is an ODBC driver for UNIX and Linux that accesses MS SQL Server by using the Windows MS SQL Server ODBC driver.

The components that you need to install on your client and server machines to provide ODBC access from PHP to Microsoft SQL Server data.

What You Need to Install

The ODBC-ODBC Bridge allows ODBC applications on one machine to access ODBC drivers on a remote machine.

The ODBC-ODBC Bridge consists of a client ODBC driver (which you install on the machine where PHP is running) and a server (which you install on a Windows machine where the Microsoft SQL Server ODBC driver is installed).

Refer to the following example to see what you need to install on your client and server machines:

Data Sources

An ODBC data source is a named resource that the application passes to the ODBC driver manager. The data source tells the driver manager which ODBC driver to load and which connection attributes to use.

With the ODBC-ODBC Bridge, there are two data sources to consider. The first data source is an ODBC-ODBC Bridge Client one on your client machine. This data source tells the driver manager to use the ODBC-ODBC Bridge Client and sets a number of attributes for the ODBC-ODBC Bridge Client. The attributes tell the ODBC-ODBC Bridge Client which server to connect to and which data source on the remote machine to use.

A typical ODBC-ODBC Bridge Client data source looks like this:

[mydatasource]
# Driver tells the driver manager which ODBC driver to use
Driver = ODBC-ODBC Bridge
# Description is a description of this data source
Description = connect to SQL Server on windows
# ServerPort is the name of the machine where the ODBC-ODBC Bridge Server is running
# and the port on which it is listening. The default port is 8888.
ServerPort = windows_server:8888

# LogonUser is a valid user account on the windows_server machine
# LogonAuth is LogonUser's password
LogonUser = my_windows_username
LogonAuth = LogonUsers_password

# TargetDSN is the name of the data source on windows_server to connect to
TargetDSN = windows_server_dsn
# TargetUser and TargetAuth are synonomous with the ODBC connection
# attributes UID and PWD and specify the user and password to use for
# the database login - if required.
#
TargetUser = db_username
TargetAuth = TargetUsers_password

We will describe these attributes in the following sections.

Note When using PHP, you do not need to specify TargetUser and TargetAuth in the data source, as these are passed in to the odbc_connect function.

Authentication

There are two levels of authentication you need to be aware of:

  1. ODBC-ODBC Bridge Server authentication

    By default, the ODBC-ODBC Bridge Server needs to authenticate the client and become the specified user on the windows_server machine. To do this, the ODBC-ODBC Bridge Client needs to specify the data source attributes LogonUser and LogonAuth. LogonUser is the name of a user who has permission to log on locally to the windows_server machine and LogonAuth is that user’s password. A user who has log on locally permissions is defined as a user who can log on at the console of windows_server. If LogonUser and LogonAuth are valid, the ODBC-ODBC Bridge Server becomes the LogonUser.

    Note You can turn off ODBC-ODBC Bridge Server authentication, but this has various implications (see the ODBC-ODBC Bridge manual).

  2. MS SQL Server authentication

    When you create a MS SQL Server data source in the Windows ODBC Administrator, you have the choice of:

    • With Integrated Windows authentication

      This is sometimes called trusted connections. In this situation, MS SQL Server examines the user on the Windows machine that is communicating with it and no SQL Server user name or password are required.

    • With SQL Server authentication

      In this scenario, MS SQL Server requires a database user name and password that your database administrator will have set up. If this is your situation, the ODBC connection attributes UID and PWD must be specified at the client end (you do this with the second and third arguments to odbc_connect).

This may be better explained with the aid of an example. Suppose you have an account on the windows_server machine and your username is Fred Bloggs and your password is mypassword. Your database administrator has set up the SQL Server instance with SQL Server authentication active and has set you up an account for the database with username dbuser and password dbpassword. To connect to this database, your ODBC-ODBC Bridge Client data source would like this:

[mydatasource]
# Driver tells the driver manager which ODBC driver to use
Driver = ODBC-ODBC Bridge
# Description is a description of this data source
Description = connect to SQL Server on windows

# ServerPort is the name of the machine where the ODBC-ODBC Bridge Server is running
# and the port on which it is listening. The default port is 8888.
ServerPort = windows_server:8888

# LogonUser is a valid user account on the windows_server machine
# LogonAuth is LogonUser's password
LogonUser = Fred Bloggs
LogonAuth = mypassword

# TargetDSN is the name of the data source on the windows_server to connect to
TargetDSN = windows_server_dsn
# TargetUser and TargetAuth are synonymous with the ODBC connection
# attributes UID and PWD and specify the user and password to use for
# the database login - if required.
#

Note When using PHP, you do not need to specify TargetUser and TargetAuth in the data source, as these will be passed in to the odbc_connect function.

In addition to setting up the ODBC-ODBC Bridge data source, your database user name and password have to be passed into the odbc_connect function within your PHP script. This is a typical odbc_connect connection string:

odbc_connect ( string dsn, string user, string password [, int cursor_type] )

When you use this function, you have to set string user to the user name you were given for the database and string password to the password for that user name. Using the same scenario as before, your odbc_connect call would look like:

odbc_connect ( "mydatasource", "dbuser", "dbpassword" )

ServerPort

The ServerPort attribute tells the ODBC-ODBC Bridge Client ODBC driver which server to connect to. ServerPort is the name or IP address of the server machine where the ODBC-ODBC Bridge Server Service is running and the port the Server is listening on. The port defaults to 8888 in the ODBC-ODBC Bridge Server configuration. This is not the port your database engine is listening on. Separate the server machine from the port with a colon (:) in the ServerPort attribute value. For example, windows_server:8888.

The ODBC-ODBC Bridge Server is configurable through an HTTP interface. Supposing your ODBC-ODBC Bridge Server is installed on windows.mycompany.local, you can access the ODBC-ODBC Bridge Server administration interface using the URL http://windows.mycompany.local:8890.

Note On Windows, the ODBC-ODBC Bridge Server installation sets the HTTP interface port to 8890, by default. This default setting can be changed during the ODBC-ODBC Bridge server installation and through the HTTP interface’s Configuration section.

TargetDSN

The TargetDSN attribute tells the ODBC-ODBC Bridge Client which data source on the remote server you want to access. This must be the name of a System data source as the ODBC-ODBC Bridge Server can only access System data sources. (To create a System data source, in the Microsoft ODBC Administrator, select the System DSN tab before clicking on Add).

Note For more information about creating a System DSN on Windows, see the ODBC-ODBC Bridge manual.

Where to Go Now

Use unixODBC’s isql program (included in the ODBC-ODBC Bridge distribution) to test your ODBC-ODBC Bridge Client data source. Then follow the PHP SQL Server examples in this tutorial.

Appendix A: Resources

Article Feedback

* Did this content help you?
* Please select one option based on your first choice:

(* Required Fields)