Estas funciones le permiten acceder a bases de datos Oracle 10, Oracle 9, Oracle 8 y Oracle 7 usando la Interfaz de Llamados Oracle (OCI por sus siglas en Ingl茅s). Ellas soportan la vinculaci贸n de variables PHP a recipientes Oracle, tienen soporte completo LOB, FILE y ROWID, y le permiten usar variables de definici贸n entregadas por el usuario.
Es necesario contar con las bibliotecas de cliente Oracle para usar esta extensi贸n. Los usuarios de Windows necesitar谩n bibliotecas con una versi贸n de al menos 10 para usar php_oci8.dll.
La forma m谩s conveniente de instalar todos los archivos requeridos es usar el Cliente Instant谩neo de Oracle, que est谩 disponible en: http://www.oracle.com/technology/tech/oci/instantclient/instantclient.html. Para trabajar con el m贸dulo OCI8, la versi贸n "b谩sica" del Cliente Instant谩neo de Oracle es suficiente. El Cliente Instant谩neo no necesita que est茅n definidas las variables de entorno ORACLE_SID o ORACLE_HOME. Sin embargo, puede que aun necesite definir LD_LIBRARY_PATH y NLS_LANG.
Antes de usar esta extensi贸n, aseg煤rese de haber configurado apropiadamente sus variables de entorno Oracle para que correspondan con el usuario de Oracle, as铆 como su usuario del demonio web. Estas variables deben ser configuradas antes de iniciar su servidor web. Las variables que necesita definir son las siguientes:
ORACLE_HOME
ORACLE_SID
LD_PRELOAD
LD_LIBRARY_PATH
NLS_LANG
Despu茅s de definir las variables de entorno para su usuario de servidor web, aseg煤rese tambi茅n de agregar al usuario del servidor web (nobody, www) al grupo oracle.
Si su servidor web no arranca, o falla al arrancar: Verifique que Apache est茅 enlazado con la biblioteca pthread:
# ldd /www/apache/bin/httpd libpthread.so.0 => /lib/libpthread.so.0 (0x4001c000) libm.so.6 => /lib/libm.so.6 (0x4002f000) libcrypt.so.1 => /lib/libcrypt.so.1 (0x4004c000) libdl.so.2 => /lib/libdl.so.2 (0x4007a000) libc.so.6 => /lib/libc.so.6 (0x4007e000) /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)Si libpthread no se encuentra en la lista, necesita re-instalar Apache:
Por favor note que en algunos sistemas, como UnixWare, se trata de libthread en lugar de libpthread. PHP y Apache deben configurarse con EXTRA_LIBS=-lthread.
El comportamiento de estas funciones est谩 afectado por los valores definidos en php.ini.
Tabla 1. OCI8 Configuration Options
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| oci8.privileged_connect | "0" | PHP_INI_SYSTEM | Available since PHP 5.1.2. |
| oci8.max_persistent | "-1" | PHP_INI_SYSTEM | Available since PHP 5.1.2. |
| oci8.persistent_timeout | "-1" | PHP_INI_SYSTEM | Available since PHP 5.1.2. |
| oci8.ping_interval | "60" | PHP_INI_SYSTEM | Available since PHP 5.1.2. |
| oci8.statement_cache_size | "20" | PHP_INI_SYSTEM | Available since PHP 5.1.2. |
| oci8.default_prefetch | "10" | PHP_INI_SYSTEM | Available since PHP 5.1.2. |
| oci8.old_oci_close_semantics | "0" | PHP_INI_SYSTEM | Available since PHP 5.1.2. |
A continuaci贸n se presenta una corta explicaci贸n de las directivas de configuraci贸n.
This option enables privileged connections using external credentials (OCI_SYSOPER, OCI_SYSDBA).
The maximum number of persistent OCI8 connections per process. Setting this option to -1 means that there is no limit.
The maximum length of time (in seconds) that a given process is allowed to maintain an idle persistent connection. Setting this option to -1 means that idle persistent connections will be maintained forever.
The length of time (in seconds) that must pass before issuing a ping during oci_pconnect(). When set to 0, persistent connections will be pinged every time they are reused. To disable pings completely, set this option to -1.
Nota: Disabling pings will cause oci_pconnect() calls to operate at the highest efficiency, but may cause PHP to not detect faulty connections, such as those caused by network partitions, or if the Oracle server has gone down since PHP connected, until later in the script. Consult the oci_pconnect() documentation for more information.
This option enables statement caching, and specifies how many statements to cache. To disable statement caching just set this option to 0.
Nota: A larger cache can result in improved performance, at the cost of increased memory usage.
This option enables statement prefetching and sets the default number of rows that will be fetched automatically after statement execution.
Nota: A larger prefetch can result in improved performance, at the cost of increased memory usage.
This option controls oci_close() behaviour. Enabling it means that oci_close() will do nothing; the connection will not be closed until the end of the script. This is for backward compatibility only. If you find that you need to enable this setting, you are strongly encouraged to remove the oci_close() calls from your application instead of enabling this option.
Estas constantes est谩n definidas por esta extensi贸n y estar谩n disponibles solamente cuando la extensi贸n ha sido o bien compilada dentro de PHP o grabada din谩micamente en tiempo de ejecuci贸n.
Statement execution mode. Statement is not committed automatically when using this mode.
Statement execution mode. Use this mode if you don't want to execute the query, but get the select-list's description.
Statement execution mode. Statement is automatically committed after oci_execute() call.
Statement fetch mode. Used when the application knows in advance exactly how many rows it will be fetching. This mode turns prefetching off for Oracle release 8 or later mode. Cursor is cancelled after the desired rows are fetched and may result in reduced server-side resource usage.
Used with oci_bind_by_name() when binding BFILEs.
Used with oci_bind_by_name() when binding CFILEs.
Used with oci_bind_by_name() when binding CLOBs.
Used with oci_bind_by_name() when binding BLOBs.
Used with oci_bind_by_name() when binding ROWIDs.
Used with oci_bind_by_name() when binding cursors, previously allocated with oci_new_descriptor().
Used with oci_bind_by_name() when binding named data types. Note: in PHP < 5.0 it was called OCI_B_SQLT_NTY.
The same as OCI_B_BFILE.
The same as OCI_B_CFILEE.
The same as OCI_B_CLOB.
The same as OCI_B_BLOB.
The same as OCI_B_ROWID.
The same as OCI_B_NTY.
Default mode of oci_fetch_all().
Alternative mode of oci_fetch_all().
Used with oci_fetch_all() and oci_fetch_array() to get an associative array as a result.
Used with oci_fetch_all() and oci_fetch_array() to get an enumerated array as a result.
Used with oci_fetch_all() and oci_fetch_array() to get an array with both associative and number indices.
Used with oci_fetch_array() to get empty array elements if field's value is NULL.
Used with oci_fetch_array() to get value of LOB instead of the descriptor.
This flag tells oci_new_descriptor() to initialize new FILE descriptor.
This flag tells oci_new_descriptor() to initialize new LOB descriptor.
This flag tells oci_new_descriptor() to initialize new ROWID descriptor.
The same as OCI_DTYPE_FILE.
The same as OCI_DTYPE_LOB.
The same as OCI_DTYPE_ROWID.
Used with oci_connect() to connect as SYSOPER using external credentials (oci8.privileged_connect should be enabled for this).
Used with oci_connect() to connect as SYSDBA using external credentials (oci8.privileged_connect should be enabled for this).
Used with OCI-Lob->flush to free buffers used.
Used with OCI-Lob->writeTemporary to indicate explicilty that temporary CLOB should be created.
Used with OCI-Lob->writeTemporary to indicate explicilty that temporary BLOB should be created.
Ejemplo 2. Insertar con variables enlazadas
|
Ejemplo 3. Inserci贸n de datos en una columna CLOB
|
Es posible acceder f谩cilmente a procedimientos almacenados en la misma forma en que lo har铆a desde la l铆nea de comandos.
Ejemplo 4. Uso de Procedimientos Almacenados
|
La extensi贸n oci8 le ofrece 3 funciones diferentes para conectarse con Oracle. Depende de usted usar la funci贸n m谩s apropiada para su aplicaci贸n, y la informaci贸n en esta secci贸n tiene la intenci贸n de ayudarle a realizar una selecci贸n informada.
Conectarse a un servidor Oracle es una operaci贸n razonablemente costosa, en t茅rminos del tiempo que toma en ser completada. La funci贸n oci_pconnect() usa un cach茅 persistente de conexiones que puede ser re-usado a trav茅s de peticiones de diferentes scripts. Esto quiere decir que usualmente s贸lo se incurrir谩 en el costo de conexi贸n una vez por proceso php (o hijo de apache).
Si su aplicaci贸n se conecta a Oracle usando un conjunto de credenciales diferente para cada usuario web, el cach茅 persistente usado por oci_pconnect() ser谩 menos 煤til a medida que el n煤mero de usuarios concurrentes se incrementa, al punto en que puede empezar a afectar adversamente el rendimiento general de su servidor Oracle debido al mantenimiento de demasiadas conexiones en reposo. Si su aplicaci贸n est谩 estructurada de este modo, es recomendable que configure su aplicaci贸n usando los parm谩metros oci8.max_persistent y oci8.persistent_timeout (estos le dar谩n control sobre el tama帽o y tiempo de vida del cach茅 de conexiones persistentes) o use oci_connect() en su lugar.
Tanto oci_connect() como oci_pconnect() emplean un cach茅 de conexiones; si realiza m煤ltiples llamadas a oci_connect() en un script dado, usando los mismo par谩metros, la segunda llamada y dem谩s despu茅s de 茅sta devolver谩n el gestor de conexi贸n existente. El cach茅 usado por oci_connect() es limpiado al final de la ejecuci贸n del script, o cuando se cierra el gestor de conexi贸n expl铆citamente. oci_pconnect() tiene un comportamiento similar, aunque su cach茅 es mantenido por separado y sobrevive entre m煤ltiples peticiones.
Es importante recordar esta caracter铆stica del uso de cach茅s, ya que da la apariencia de que dos gestores no est谩n aislados transaccionalmente (en realidad son el mismo gestor de conexi贸n, as铆 que no hay separaci贸n de ning煤n tipo). Si su aplicaci贸n necesita dos conexiones separadas, aisladas transaccionalmente, deber铆a usar oci_new_connect().
oci_new_connect() siempre crea una nueva conexi贸n al servidor Oracle, independientemente de cualquier otra conexi贸n que pueda existir. Las aplicaciones con alto tr谩fico web deber铆an tratar de evitar el uso de oci_new_connect(), especialmente en las secciones m谩s ocupadas de la aplicaci贸n.
Tabla 2. El controlador soporta los siguientes tipos cuando enlaza par谩metros con la funci贸n oci_bind_by_name():
| Tipo | Asociaci贸n |
|---|---|
| SQLT_NTY | Asigna un tipo nativo de colecci贸n desde un objeto colecci贸n PHP, tal como aquellos creados por oci_new_collection(). |
| SQLT_BFILEE | Asigna un descriptor nativo, tal como aquellos creados por oci_new_descriptor(). |
| SQLT_CFILEE | Asigna un descriptor nativo, tal como aquellos creados por oci_new_descriptor(). |
| SQLT_CLOB | Asigna un descriptor nativo, tal como aquellos creados por oci_new_descriptor(). |
| SQLT_BLOB | Asigna un descriptor nativo, tal como aquellos creados por oci_new_descriptor(). |
| SQLT_RDD | Asigna un descriptor nativo, tal como aquellos creados por oci_new_descriptor(). |
| SQLT_NUM | Convierte el par谩metro PHP a un tipo largo 'C', y lo enlaza a ese valor. |
| SQLT_RSET | Asigna un gestor de sentencia nativo, tal como aquellos creados por oci_parse() o aquellos recuperados desde otras consultas OCI. |
| SQLT_CHR y cualquier otro tipo | Convierte el par谩metro PHP a un tipo cadena y lo enlaza como una cadena. |
Tabla 3. Los siguientes tipos son soportados cuando se recuperan columnas desde un conjunto de resultados:
| Tipo | Asociaci贸n |
|---|---|
| SQLT_RSET | Crea un recurso de sentencia oci para representar el cursor. |
| SQLT_RDD | Crea un objeto ROWID. |
| SQLT_BLOB | Crea un objeto LOB. |
| SQLT_CLOB | Crea un objeto LOB. |
| SQLT_BFILE | Crea un objeto LOB. |
| SQLT_LNG | Enlazado como SQLT_CHR, devuelto como una cadena |
| SQLT_LBI | Enlazado como SQLT_BIN, devuelto como una cadena |
| Any other type | Enlazado como SQLT_BIN, devuelto como una cadena |