Accessing Microsoft SQL Server from PHP under Apache on UNIX and 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.
Contents
- Prerequisites
- Examples: How to connect PHP with SQL Server and retrieve data
- Example: How to call SQL Server procedures from PHP
- PHP Data Objects (PDO)
- Alternative PHP and SQL Server solution
Prerequisites
PHP 4.2 or Later
To check which version of PHP you're 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 get 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's 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 Red Hat, we used the redhat-config-packages package manager to install PHP from RPMs.
Installing PHP from packages on Ubuntu
- On the System menu, choose Administration, and then choose Synaptic Package Manager.
- Enter the administrative (sudo) password when prompted.
- In Synaptic Package Manager, mark php5/ and php5-odbc for installation.
Agree to install dependent packages (libapache2-mod-php5, php5-common and unixodbc) when prompted .
- If you want to run PHP from the command line as well as from under Apache, mark php-cli for installation.
- Choose the Apply button.
Installing PHP from RPMs on Red Hat
- Select the Red Hat icon, and then choose Add/Remove Applications from the System Settings menu.
- Enter the root password when prompted.
- Add the php and php-odbc Web Server packages.
- Choose the Update button.
Testing PHP
Create a PHP script that calls the phpinfo
function. phpinfo
tests whether your PHP distribution is working correctly. The 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:
- Create a file called
phpinfo.php
. - Add these lines to phpinfo.php:
#!/bin/bash # This is a simple one liner that amongst other things returns relevant PHP information <?php phpinfo() ?>
- Save this file, and then from the command line, enter:
php phpinfo.php > newhtmlfile.html
This redirects the output from
phpinfo
into an HTML file callednewhtmlfile.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're 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 Red Hat, 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 run the example PHP scripts from the shell prompt.
SQL Server ODBC driver
We used our SQL Server ODBC driver.
- Download the SQL Server ODBC driver for your PHP client platform.
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 our web site.
- Install and license the SQL Server ODBC driver on the machine where PHP is installed.
For installation instructions, refer to the ODBC driver documentation. Refer to the documentation to find out which environment variables you need to set (
LD_LIBRARY_PATH
,LIBPATH
,LD_RUN_PATH
, andSHLIB_PATH
depending on the driver, platform and linker). - 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
- Use isql to test the new data source. For example:
cd /usr/local/easysoft/unixODBC/bin ./isql -v MSSQL-PHP
At the prompt, enter
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 user_name
and password
placeholders with appropriate values for your database.
To run this script:
- Copy the script shown below into a new file.
- Replace
data_source_name
,database_user_name
, anddatabase_password
with your SQL Server ODBC data source, login name and password. - 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. - 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_user_name and database_password with the SQL Server database user name and password. */ $data_source='data_source_name'; $user='database_user_name'; $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:
- Copy the script shown below into a new file.
- Replace
data_source_name
,database_user_name
, anddatabase_password
with your SQL Server ODBC data source, login name and password. - 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_user_name and database_password with the SQL Server database user name and password. */ $data_source='data_source_name'; $user='database_user_name'; $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:
- Copy the script shown below into a new file.
- Replace
datasource_name
,database_user_name
, anddatabase_password
with your SQL Server ODBC data source, login name and password. - Save the file. For example,
/tmp/mssql-php-retrieve-data.php
. - 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_user_name and database_password with the SQL Server database user name and password. */ $data_source='datasource_name'; $user='database_user_name'; $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's 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_user_name and database_password with the SQL Server database user name and password. */ $data_source ='datasource_name'; $user = 'database_user_name'; $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 by using 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, refer to earlier in this tutorial.
Installing PDO and PDO_ODBC
We tested the SQL Server ODBC driver with PDO and 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 by using 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, enter ./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 tophp.ini
:extension=pdo_odbc.so
If you don't have an existing
php.ini
file, the PHP functionphpinfo()
will report where PHP expects to find this configuration file. - If you want to use PDO_ODBC with PHP running under Apache, include the
--with-apxs2
option on the configure line. Specify the directory where your Apache executables are located in--with-apxs2
option value. For example,--with-apxs2=/usr/local/apache2/bin/apxs
.You also need to ensure that:
LoadModule php5_module modules/libphp5.so
is uncommented in (or added to)httpd.conf
.AddType application/x-httpd-php .php .phtml
is added tohttpd.conf
.
For more information about building PHP as an Apache module, refer to Enabling ODBC support in PHP under Apache.
Connecting to SQL Server through PDO
To use the PDO interface to connect to SQL Server by using 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 SQL Server by using the Windows 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 find out 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's 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:
- ODBC driver For this tutorial, you need the Microsoft SQL Server ODBC driver or the Microsoft SQL Server Native Client. You don't need to install the SQL Server ODBC driver or SQL Server Native Client 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
.
ODBC data sources
An ODBC data source is a named resource that the application passes to the ODBC Driver Manager. The ODBC 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_user_name 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_user_name TargetAuth = TargetUsers_password
We will describe these attributes in the following sections.
Note When using PHP, you don't 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:
-
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 attributesLogonUser
andLogonAuth
.LogonUser
is the name of a user who has permission to log on locally to the windows_server machine andLogonAuth
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. IfLogonUser
andLogonAuth
are valid, the ODBC-ODBC Bridge server becomes theLogonUser
.Note You can turn off ODBC-ODBC Bridge server authentication, but this has various implications (refer to the ODBC-ODBC Bridge manual).
-
Microsoft SQL Server authentication
When you create a Microsoft SQL Server data source in the Windows ODBC Data Source Administrator, you have the choice of:
-
With Integrated Windows authentication
This is sometimes called trusted connections. Microsoft 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
Microsoft 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
andPWD
must be specified at the client end (you do this with the second and third arguments toodbc_connect
).
-
With Integrated Windows authentication
This may be better explained with the aid of an example. Suppose you have an account on the windows_server
machine and your user name is Fred Bloggs
and your password is mypassword
. Your database administrator has set up the SQL Server instance with SQL Server authentication and has set you up an account for the database with user name dbuser
and password
dbpassword. To connect to this database, your ODBC-ODBC Bridge client data source would be:
[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 don't 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. Your odbc_connect
call will look like:
odbc_connect ( "mydatasource", "dbuser", "dbpassword" )
ServerPort
The ServerPort
attribute tells the ODBC-ODBC Bridge client which server to connect to. ServerPort
is the name or IP address of the server machine where the ODBC-ODBC Bridge server 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 this 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 Data Source Administrator, select the System DSN tab, and then choose Add).
Note For more information about creating a system DSN on Windows, refer to 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.