Php new pdo odbc

ODBC and DB2 Functions (PDO_ODBC)

PDO_ODBC is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to databases through ODBC drivers or through the IBM DB2 Call Level Interface (DB2 CLI) library. PDO_ODBC currently supports three different «flavours» of database drivers: ibm-db2

Supports access to IBM DB2 Universal Database, Cloudscape, and Apache Derby servers through the free DB2 express-C client.

Supports access to database servers through the unixODBC driver manager and the database’s own ODBC drivers.

Offers a compile option for ODBC driver managers that are not explicitly supported by PDO_ODBC.

On Windows, php_pdo_odbc.dll has to be enabled as extension in php.ini . It is linked against the Windows ODBC Driver Manager so that PHP can connect to any database cataloged as a System DSN.

Installation

    PDO_ODBC is included in the PHP source. You can compile the PDO_ODBC extension as either a static or shared module using the following configure commands. ibm_db2
./configure --with-pdo-odbc=ibm-db2,/opt/IBM/db2/V8.1/

To build PDO_ODBC with the ibm-db2 flavour, you have to have previously installed the DB2 application development headers on the same machine on which you are compiling PDO_ODBC. The DB2 application development headers are an installable option in the DB2 servers, and are also available as part of the DB2 Application Development Client freely available for download from the IBM developerWorks » website. If you do not supply a location for the DB2 libraries and headers to the configure command, PDO_ODBC defaults to /home/db2inst1/sqllib . unixODBC

./configure --with-pdo-odbc=unixODBC,/usr/local

If you do not supply a location for the unixODBC libraries and headers to the configure command, PDO_ODBC defaults to /usr/local . generic

./configure --with-pdo-odbc=generic,/usr/local,libname,ldflags,cflags

Predefined Constants

The constants below are defined by this driver, and will only be available when the extension has been either compiled into PHP or dynamically loaded at runtime. In addition, these driver-specific constants should only be used if you are using this driver. Using driver-specific attributes with another driver may result in unexpected behaviour. PDO::getAttribute() may be used to obtain the PDO::ATTR_DRIVER_NAME attribute to check the driver, if your code can run against multiple drivers.

Читайте также:  Interface with variables in java

PDO::ODBC_ATTR_USE_CURSOR_LIBRARY ( int )

  • PDO::ODBC_SQL_USE_IF_NEEDED (the default): use the ODBC cursor library when needed.
  • PDO::ODBC_SQL_USE_DRIVER : never use the ODBC cursor library.
  • PDO::ODBC_SQL_USE_ODBC : always use the ODBC cursor library.

PDO::ODBC_ATTR_ASSUME_UTF8 ( bool )

Windows only. If true , UTF-16 encoded character data ( CHAR , VARCHAR and LONGVARCHAR ) is converted to UTF-8 when reading from or writing data to the database. If false (the default), character encoding conversion may be done by the driver.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini .

PDO_ODBC Configuration Options

Name Default Changeable Changelog
pdo_odbc.connection_pooling «strict» PHP_INI_ALL
pdo_odbc.db2_instance_name NULL PHP_INI_SYSTEM This deprecated feature will certainly be removed in the future.

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here’s a short explanation of the configuration directives.

Whether to pool ODBC connections. Can be one of «strict» , «relaxed» or «off» (equals to «» ). The parameter describes how strict the connection manager should be when matching connection parameters to existing pooled connections. strict is the recommend default, and will result in the use of cached connections only when all the connection parameters match exactly. relaxed will result in the use of cached connections when similar connection parameters are used. This can result in increased use of the cache, at the risk of bleeding connection information between (for example) virtual hosts.

This setting can only be changed from the php.ini file, and affects the entire process; any other modules loaded into the process that use the same ODBC libraries will be affected too, including the Unified ODBC extension.

relaxed matching should not be used on a shared server, for security reasons.

Leave this setting at the default strict setting unless you have good reason to change it.

If you compile PDO_ODBC using the db2 flavour, this setting sets the value of the DB2INSTANCE environment variable on Linux and UNIX operating systems to the specified name of the DB2 instance. This enables PDO_ODBC to resolve the location of the DB2 libraries and make cataloged connections to DB2 databases.

This setting can only be changed from the php.ini file, and affects the entire process; any other modules loaded into the process that use the same ODBC libraries will be affected too, including the Unified ODBC extension.

This setting has no effect on Windows.

Table of Contents

Источник

PDO_ODBC DSN

The DSN prefix is odbc: . If you are connecting to a database cataloged in the ODBC driver manager or the DB2 catalog, you can append the cataloged name of the database to the DSN.

The name of the database as cataloged in the ODBC driver manager or the DB2 catalog. Alternately, you can provide a complete ODBC connection string to connect to a database as described at » http://www.connectionstrings.com/.

The name of the user for the connection. If you specify the user name in the DSN, PDO ignores the value of the user name argument in the PDO constructor.

The password of the user for the connection. If you specify the password in the DSN, PDO ignores the value of the password argument in the PDO constructor.

Examples

Example #1 PDO_ODBC DSN example (ODBC driver manager)

The following example shows a PDO_ODBC DSN for connecting to an ODBC database cataloged as testdb in the ODBC driver manager:

Example #2 PDO_ODBC DSN example (IBM DB2 uncataloged connection)

The following example shows a PDO_ODBC DSN for connecting to an IBM DB2 database named SAMPLE using the full ODBC DSN syntax:

odbc:DRIVER=;HOSTNAME=localhost;PORT=50000;DATABASE=SAMPLE;PROTOCOL=TCPIP;UID=db2inst1;PWD=ibmdb2;

Example #3 PDO_ODBC DSN example (Microsoft Access uncataloged connection)

The following example shows a PDO_ODBC DSN for connecting to a Microsoft Access database stored at C:\db.mdb using the full ODBC DSN syntax:

odbc:Driver=;Dbq=C:\\db.mdb;Uid=Admin

Источник

Подключения и управление подключениями

Соединения устанавливаются автоматически при создании объекта PDO от его базового класса. Не имеет значения, какой драйвер вы хотите использовать; вы всегда используете имя базового класса. Конструктор класса принимает аргументы для задания источника данных (DSN), а также необязательные имя пользователя и пароль (если есть).

Пример #1 Подключение к MySQL

В случае возникновения ошибки при подключении будет выброшено исключение PDOException . Его можно перехватить и обработать, либо оставить на откуп глобальному обработчику ошибок, который вы задали функцией set_exception_handler() .

Пример #2 Обработка ошибок подключения

try $dbh = new PDO ( ‘mysql:host=localhost;dbname=test’ , $user , $pass );
foreach( $dbh -> query ( ‘SELECT * from FOO’ ) as $row ) print_r ( $row );
>
$dbh = null ;
> catch ( PDOException $e ) print «Error!: » . $e -> getMessage () . «
» ;
die();
>
?>

Если ваше приложение не перехватывает исключение PDO конструктора, движок zend выполнит стандартные операции для завершения работы скрипта и вывода обратной трассировки. В этой трассировке будет содержаться детальная информация о соединении с базой данных, включая имя пользователя и пароль. Ответственность за перехват исключений лежит на вас. Перехватить исключение можно явно (с помощью выражения catch ), либо неявно, задав глобальный обработчик ошибок функцией set_exception_handler() .

При успешном подключении к базе данных в скрипт будет возвращён созданный объект PDO. Соединение остаётся активным на протяжении всего времени жизни объекта. Чтобы закрыть соединение, необходимо уничтожить объект путём удаления всех ссылок на него (этого можно добиться, присваивая null всем переменным, указывающим на объект). Если не сделать этого явно, PHP автоматически закроет соединение по окончании работы скрипта.

Замечание: Если существуют другие ссылки на данный экземпляр PDO (например, из объекта PDOStatement или другие переменные, ссылающиеся на него), они также должны быть удалены (например, присвоением null переменной, ссылающейся на PDOStatement).

Пример #3 Закрытие соединения

$dbh = new PDO ( ‘mysql:host=localhost;dbname=test’ , $user , $pass );
// здесь мы каким-то образом используем соединение
$sth = $dbh -> query ( ‘SELECT * FROM foo’ );

// соединение больше не нужно, закрываем
$sth = null ;
$dbh = null ;
?>

Во многих приложениях может оказаться полезным использование постоянных соединений к базам данных. Постоянные соединения не закрываются при завершении работы скрипта, они кешируются и используются повторно, когда другой скрипт запрашивает соединение с теми же учётными данными. Постоянные соединения позволяют избежать создания новых подключений каждый раз, когда требуется обмен данными с базой, что в результате даёт прирост скорости работы таких приложений.

Пример #4 Постоянные соединения

$dbh = new PDO ( ‘mysql:host=localhost;dbname=test’ , $user , $pass , array(
PDO :: ATTR_PERSISTENT => true
));
?>

Значение параметра PDO::ATTR_PERSISTENT преобразуется в логическое значение ( bool ) (включить/отключить постоянные подключения), если это не числовая строка ( string ), которая в этом случае позволяет использовать несколько пулов постоянных подключений. Это полезно, если разные соединения используют несовместимые настройки, например, разные значения PDO::MYSQL_ATTR_USE_BUFFERED_QUERY .

Замечание:

Чтобы использовать постоянные соединения, необходимо добавить константу PDO::ATTR_PERSISTENT в массив параметров драйвера, который передаётся конструктору PDO. Если просто задать этот атрибут функцией PDO::setAttribute() уже после создания объекта, драйвер не будет использовать постоянные соединения.

Замечание:

Если вы используете PDO ODBC драйвер и ваши ODBC библиотеки поддерживают объединение подключений в пул (ODBC Connection Pooling) (unixODBC и Windows точно поддерживают, но могут быть и другие), то рекомендуется вместо постоянных соединений пользоваться этим пулом. Пул подключений ODBC доступен всем модулям текущего процесса; если PDO сам кеширует соединение, то это соединение будет недоступно другим модулям и не попадёт в пул. В результате каждый модуль будет создавать дополнительные подключения для своих нужд.

User Contributed Notes

  • PDO
    • Введение
    • Установка и настройка
    • Предопределённые константы
    • Подключения и управление подключениями
    • Транзакции и автоматическая фиксация изменений
    • Подготовленные запросы и хранимые процедуры
    • Ошибки и их обработка
    • Большие объекты (LOB)
    • PDO
    • PDOStatement
    • PDOException
    • Драйверы PDO

    Источник

Оцените статью