You are on page 1of 20

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 and SQL Server Express
When developing this tutorial, we accessed SQL Server 20002012 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 distributionCentOS, 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. Apache 2.0 or later. SQL Server ODBC driver.

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, php5common and unixodbc). 4. If you want to run PHP from the command line as well as from under Apache, mark phpcli 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:


3. #!/bin/bash 4. # This is a simple one liner that amongst other things returns relevant PHP information 5. <? 6. phpinfo() 7. ?>

8. 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 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:
4. [MSSQL-PHP] 5. Driver = Easysoft ODBC-SQL Server 6. Server = my_machine\SQLEXPRESS 7. User = my_domain\my_user 8. Password = my_password 9. # If the database you want to connect to is the default 10. # for the SQL Server login, omit this attribute Database = Northwind

11. Use isql to test the new data source. For example:
12. 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 servers 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 servers host name or IP address. 4. To run the script from the command line, save the file. For example, /tmp/php-mssqlconnection.php. Then run $ php /tmp/php-mssql-connection.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 servers 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> <? /* 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-retrievedata.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.
<? /* 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:

Prepared statements and bound parameters. Transactions. Large objects (LOBs). SQLState error codes. Scrollable cursors.

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:

PHP 5.3.10 running both standalone and under Apache 2.2.22. (Installed from packages.) PHP 5.4.5 running both standalone and under Apache 2.4.2. (Built form source.)

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 php5-cli php5-odbc Notes Enables PHP scripts to be run standalone. Automatically supports PDO. 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. The version of PDO_ODBC included in the php5-odbc package is built to support libodbc1 the unixODBC Driver Manager. The libodbc1 package contains the unixODBC libraries and is a dependent package of php5-odbc. apache2Apache HTTP server. This is the non-threaded version as libapache2-mod-php5 is mpm-prefork not compatible with the threaded version of Apache (apache2-mpm-worker). PHP module for Apache. Automatically supports PDO. Enables PHP to be run libapache2- under Apache. The Apache HTTP server was automatically configured to load mod-php5 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

If you build PDO_ODBC as a shared module, you need to update the php.ini file so that PDO_ODBC will be loaded automatically when PHP runs. To do this, add the following line to php.ini:

extension=pdo_odbc.so

If you do not have an existing php.ini file, the PHP function phpinfo() will report where PHP expects to find this configuration file.

If you want to use PDO_ODBC with PHP running under Apache, include the --withapxs2 option on the configure line. Specify the directory where your Apache executables are located in --with-apxs2 option value. For example, --withapxs2=/usr/local/apache2/bin/apxs. You also need to ensure that:
o o LoadModule php5_module modules/libphp5.so

is uncommented in (or added is added to httpd.conf.

to) httpd.conf.
AddType application/x-httpd-php .php .phtml

For more information about building PHP as an Apache module, see Enabling ODBC support in PHP under Apache.

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
<? /* 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.)
<? /* 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 = NULL; $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.

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:

Client Machine

This is the machine you want to run PHP on. You need to have installed: PHP The minimum version required. The ODBC-ODBC Bridge Client The ODBC-ODBC Bridge Client is an ODBC driver that talks to the ODBC-ODBC Bridge Server and therefore your remote ODBC data source. You need to install the ODBC-ODBC Bridge Client and the unixODBC Driver Manager. ODBC-ODBC Bridge distributions include the unixODBC Driver Manager. There is no need to install the ODBC-ODBC Bridge Server on this machine. Refer to the ODBC-ODBC Bridge manual for installation instructions. Server machine This is the machine where you have (or can install) an ODBC driver for the database you want to access. You need to have installed:
o o o

ODBC driver For this tutorial, you need the Microsoft SQL Server ODBC driver, and it is available in Microsoft Data Access Components (MDAC), the Microsoft SQL Server Native Client and the Microsoft SQL Server 2008 Native Client. You do not need install the MS SQL Server ODBC driver on the same machine as your SQL Server database. The ODBC-ODBC Bridge Server. The ODBC-ODBC Bridge Server is an ODBC application, which accepts connections from the ODBC-ODBC Bridge Client and relays them to your target ODBC data source. You need to license the ODBC-ODBC Bridge Server, and trial licenses may be obtained during the installation. Refer to the ODBC-ODBC Bridge manual for installation instructions. In the following sections, we refer to the Server machine as windows_server.

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 ODBCODBC 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 # LogonAuth LogonUser = LogonAuth = is a valid user account on the windows_server machine is LogonUser's password my_windows_username 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 users 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:
o

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 # LogonAuth LogonUser = LogonAuth = is a valid user account on the windows_server machine is LogonUser's password Fred Bloggs 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 ODBCODBC 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 interfaces 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 unixODBCs 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

PHP SQL Server solutions from Easysoft: o SQL Server ODBC driver o ODBC-ODBC Bridge http://www.php.net Enabling ODBC support in PHP under Apache SQL Server ODBC Driver Knowledge Base ODBC-ODBC Bridge Knowledge Base Linux/UNIX ODBC -- everything you need to know about ODBC on Linux and UNIX platforms. 64-bit ODBC -- everything you need to know about ODBC on 64-bit Linux, UNIX and Windows platforms. Easysoft Guide to ODBC Diagnostics & Error Status Codes

You might also like