Forum und email

Funciones de Oracle

Introducción

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.

Requisitos

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.

Note: Esta extensión ya no ofrece soporte para las bibliotecas cliente de Oracle 8. Sin embargo, aun es posible conectarse a servidores Oracle 8 siempre y cuando la biblioteca cliente (v.9+) lo soporte.

La forma más conveniente de instalar todos los archivos requeridos es usar el Cliente Instantáneo de Oracle, que está disponible en: » https://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
Para más información sobre variables de entorno de Oracle usadas con menos frecuencia como TNS_ADMIN, TWO_TASK, ORA_TZFILE, y los varios parámetros de globalización de Oracle como ORA_NLS33, ORA_NLS10 y las variables NLS_* refiérase a la documentación de Oracle.

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.

Note: 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:
# cd /usr/src/apache_1.3.xx
# make clean
# LIBS=-lpthread ./config.status
# make
# make install

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.

Configuración en tiempo de ejecución

El comportamiento de estas funciones está afectado por los valores definidos en php.ini.

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.

oci8.privileged_connect boolean

This option enables privileged connections using external credentials (OCI_SYSOPER, OCI_SYSDBA).

oci8.max_persistent int

The maximum number of persistent OCI8 connections per process. Setting this option to -1 means that there is no limit.

oci8.persistent_timeout int

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.

oci8.ping_interval int

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.

Note: 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.

oci8.statement_cache_size int

This option enables statement caching, and specifies how many statements to cache. To disable statement caching just set this option to 0.

Note: A larger cache can result in improved performance, at the cost of increased memory usage.

oci8.default_prefetch int

This option enables statement prefetching and sets the default number of rows that will be fetched automatically after statement execution.

Note: A larger prefetch can result in improved performance, at the cost of increased memory usage.

oci8.old_oci_close_semantics boolean

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.

Constantes predefinidas

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.

OCI_DEFAULT (integer)
Statement execution mode. Statement is not committed automatically when using this mode.
OCI_DESCRIBE_ONLY (integer)
Statement execution mode. Use this mode if you don't want to execute the query, but get the select-list's description.
OCI_COMMIT_ON_SUCCESS (integer)
Statement execution mode. Statement is automatically committed after oci_execute() call.
OCI_EXACT_FETCH (integer)
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.
OCI_SYSDATE (integer)
OCI_B_BFILE (integer)
Used with oci_bind_by_name() when binding BFILEs.
OCI_B_CFILEE (integer)
Used with oci_bind_by_name() when binding CFILEs.
OCI_B_CLOB (integer)
Used with oci_bind_by_name() when binding CLOBs.
OCI_B_BLOB (integer)
Used with oci_bind_by_name() when binding BLOBs.
OCI_B_ROWID (integer)
Used with oci_bind_by_name() when binding ROWIDs.
OCI_B_CURSOR (integer)
Used with oci_bind_by_name() when binding cursors, previously allocated with oci_new_descriptor().
OCI_B_NTY (integer)
Used with oci_bind_by_name() when binding named data types. Note: in PHP < 5.0 it was called OCI_B_SQLT_NTY.
OCI_B_BIN (integer)
SQLT_BFILEE (integer)
The same as OCI_B_BFILE.
SQLT_CFILEE (integer)
The same as OCI_B_CFILEE.
SQLT_CLOB (integer)
The same as OCI_B_CLOB.
SQLT_BLOB (integer)
The same as OCI_B_BLOB.
SQLT_RDD (integer)
The same as OCI_B_ROWID.
SQLT_NTY (integer)
The same as OCI_B_NTY.
SQLT_LNG (integer)
Used with oci_bind_by_name() to bind LONG values.
SQLT_LBI (integer)
Used with oci_bind_by_name() to bind LONG RAW values.
SQLT_BIN (integer)
Used with oci_bind_by_name() to bind RAW values.
SQLT_NUM (integer)
Used with oci_bind_array_by_name() to bind arrays of NUMBER.
SQLT_INT (integer)
Used with oci_bind_array_by_name() to bind arrays of INTEGER.
SQLT_AFC (integer)
Used with oci_bind_array_by_name() to bind arrays of CHAR.
SQLT_CHR (integer)
Used with oci_bind_array_by_name() to bind arrays of VARCHAR2. Also used with oci_bind_by_name().
SQLT_VCS (integer)
Used with oci_bind_array_by_name() to bind arrays of VARCHAR.
SQLT_AVC (integer)
Used with oci_bind_array_by_name() to bind arrays of CHARZ.
SQLT_STR (integer)
Used with oci_bind_array_by_name() to bind arrays of STRING.
SQLT_LVC (integer)
Used with oci_bind_array_by_name() to bind arrays of LONG VARCHAR.
SQLT_FLT (integer)
Used with oci_bind_array_by_name() to bind arrays of FLOAT.
SQLT_ODT (integer)
Used with oci_bind_array_by_name() to bind arrays of LONG.
SQLT_BDOUBLE (integer)
SQLT_BFLOAT (integer)
OCI_FETCHSTATEMENT_BY_COLUMN (integer)
Default mode of oci_fetch_all().
OCI_FETCHSTATEMENT_BY_ROW (integer)
Alternative mode of oci_fetch_all().
OCI_ASSOC (integer)
Used with oci_fetch_all() and oci_fetch_array() to get an associative array as a result.
OCI_NUM (integer)
Used with oci_fetch_all() and oci_fetch_array() to get an enumerated array as a result.
OCI_BOTH (integer)
Used with oci_fetch_all() and oci_fetch_array() to get an array with both associative and number indices.
OCI_RETURN_NULLS (integer)
Used with oci_fetch_array() to get empty array elements if field's value is NULL.
OCI_RETURN_LOBS (integer)
Used with oci_fetch_array() to get value of LOB instead of the descriptor.
OCI_DTYPE_FILE (integer)
This flag tells oci_new_descriptor() to initialize new FILE descriptor.
OCI_DTYPE_LOB (integer)
This flag tells oci_new_descriptor() to initialize new LOB descriptor.
OCI_DTYPE_ROWID (integer)
This flag tells oci_new_descriptor() to initialize new ROWID descriptor.
OCI_D_FILE (integer)
The same as OCI_DTYPE_FILE.
OCI_D_LOB (integer)
The same as OCI_DTYPE_LOB.
OCI_D_ROWID (integer)
The same as OCI_DTYPE_ROWID.
OCI_SYSOPER (integer)
Used with oci_connect() to connect as SYSOPER using external credentials (oci8.privileged_connect should be enabled for this).
OCI_SYSDBA (integer)
Used with oci_connect() to connect as SYSDBA using external credentials (oci8.privileged_connect should be enabled for this).
OCI_LOB_BUFFER_FREE (integer)
Used with OCI-Lob->flush to free buffers used.
OCI_TEMP_CLOB (integer)
Used with OCI-Lob->writeTemporary to indicate explicilty that temporary CLOB should be created.
OCI_TEMP_BLOB (integer)
Used with OCI-Lob->writeTemporary to indicate explicilty that temporary BLOB should be created.

Ejemplos

Example#1 Consulta básica

<?php

  $conexion 
oci_connect('hr''hr''orcl');
  if (!
$conexion) {
    
$e oci_error();
    print 
htmlentities($e['message']);
    exit;
  }

  
$consulta 'SELECT * FROM DEPARTMENTS';

  
$id_sentencia oci_parse($conexion$consulta);
  if (!
$id_sentencia) {
    
$e oci_error($conexion);
    print 
htmlentities($e['message']);
    exit;
  }

  
$r oci_execute($id_sentenciaOCI_DEFAULT);
  if (!
$r) {
    
$e oci_error($id_sentencia);
    echo 
htmlentities($e['message']);
    exit;
  }

  print 
'<table border="1">';
  while (
$fila oci_fetch_array($id_sentenciaOCI_RETURN_NULLS)) {
    print 
'<tr>';
       foreach (
$fila as $item) {
         print 
'<td>'.($item?htmlentities($item):'&nbsp;').'</td>';
       }
       print 
'</tr>';
  }
  print 
'</table>';

  
oci_close($conexion);
?>

Example#2 Insertar con variables enlazadas

<?php

  
// Antes de ejecutar, cree la tabla:
  //   CREATE TABLE MITABLA (mid NUMBER, myd VARCHAR2(20));

  
$conexion oci_connect('scott''tiger''orcl');

  
$consulta 'INSERT INTO MITABLA VALUES(:myid, :mydata)';

  
$id_sentencia oci_parse($conexion$consulta);

  
$id 60;
  
$datos 'Algún dato';

  
oci_bind_by_name($id_sentencia':myid'$id);
  
oci_bind_by_name($id_sentencia':mydata'$datos);

  
$r oci_execute($id_sentencia);

  if (
$r)
    print 
"Una fila insertada";

  
oci_close($conexion);

?>

Example#3 Inserción de datos en una columna CLOB

<?php

// Antes de ejecutar, cree la tabla:
//     CREATE TABLE mitabla (miclave NUMBER, miclob CLOB);

$conexion oci_connect('scott''tiger''orcl');

$mi_clave 12343;  // clave arbitraria para este ejemplo

$sql "INSERT INTO mitabla (miclave, miclob)
        VALUES (:miclave, EMPTY_CLOB())
        RETURNING miclob INTO :miclob"
;

$id_sentencia oci_parse($conexion$sql);
$clob oci_new_descriptor($conexionOCI_D_LOB);
oci_bind_by_name($id_sentencia":miclave"$mi_clave5);
oci_bind_by_name($id_sentencia":miclob"$clob, -1OCI_B_CLOB);
oci_execute($id_sentenciaOCI_DEFAULT);
$clob->save("Una cadena muy larga");

oci_commit($conexion);

// Recuperación de datos CLOB

$consulta 'SELECT miclob FROM mitabla WHERE miclave = :miclave';

$id_sentencia oci_parse ($conexion$consulta);
oci_bind_by_name($id_sentencia":miclave"$mi_clave5);
oci_execute($id_sentenciaOCI_DEFAULT);

print 
'<table border="1">';
while (
$fila oci_fetch_array($id_sentenciaOCI_ASSOC)) {
  
$resultado $fila['MYCLOB']->load();
  print 
'<tr><td>'.$resultado.'</td></tr>';
}
print 
'</table>';

?>

Es posible acceder fácilmente a procedimientos almacenados en la misma forma en que lo haría desde la línea de comandos.

Example#4 Uso de Procedimientos Almacenados

<?php
// por webmaster arroba remoterealty punto com
$sth oci_parse($dbh"begin proc_nueva_dir( :id_direccion, '$nombre',
 '$apellido', '$companyia', '$dir1', '$dir2', '$ciudad', '$estado',
 '$cod_postal', '$pais', :cod_error );end;"
);

// Esto llama al procedimiento almacenado proc_nueva_dir, en donde
// :id_direccion es una variable de entrada/salida y :cod_error es una
// variable de salida.
// Entonces crea la vinculación:

   
oci_bind_by_name($sth":id_direccion"$id_direccion10);
   
oci_bind_by_name($sth":cod_error"$cod_error10);
   
oci_execute($sth);

?>

Manejo de Conexiones

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.

Tipos de datos soportados por el controlador

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.
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

Table of Contents